What is the best way to validate email addresses in Vue.js using watchers?

watch: {

    email(value) {
      this.email = value;
      this.validateEmail(value);
    },
  },

  methods() {
    validateEmail() {
      // eslint-disable-next-line
      if (/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>[\\.,;:\\s@"]+)*)|(\".+\"))@((\[0-9]{1,3}.\[0-9]{1,3}.\[0-9]{1,3}.\[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(this.email)) {
        this.errmsg.email = ''
      } else this.errmsg['email'] = 'Invalid Email Address';

    },
<input class="input-mobile-email" type="text" placeholder="Your email" id="email" v-model="email" name="email" :maxlength="maxemail" @input="validateEmail" />

<button class="submit-button" data-toggle="modal" type="submit" value="Submit" data-target="#exampleModal" :class="isDisabled ? '' : 'selected'" :disabled="isDisabled">Submit</button>

How to implement email validation using watchers in Vuejs? Designed to enable the submit button only when a valid email address is entered.

Answer №1

If you want to check if an email is valid in Vue.js, you can utilize computed properties like this:

computed() {
  isValidEmail() {
    return '/^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/'.test(this.email)
  }
}

After defining this computed property, you can replace your existing isDisabled with isValidEmail

Check out a working example here: https://jsfiddle.net/u0c98kmL/

Answer №2

If you are focusing solely on email validation in your situation, the most straightforward approach would be to create a computed property for this, as suggested by Takachi. In this scenario, there is no need for any watchers.

However, if you require additional validations, consider utilizing a library like or exploring how it can be implemented.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What causes v-for to not display every object?

I have encountered an issue while trying to display search results obtained from an API. The v-for directive seems to be not rendering all the objects. Here is a glimpse of my search box: https://i.sstatic.net/Lgwe7.jpg Despite having only one item displ ...

Uploading files with a progress bar in NodeJS by utilizing Core NodeJS and the authentic Node approach

Ryan Dahl mentioned that he created NodeJS to address the file upload progress bar issue (https://youtu.be/SAc0vQCC6UQ). During its introduction in 2009, Node utilized technology available at the time before more advanced client-side javascript libraries l ...

Converting Python conditional statements to Javascript control flow

How can I achieve this task using JavaScript? I want it to output 'Found' when it finds the word words in the big_list big_list = ['this', 'is', 'a', 'long', 'list', 'of' 'words&ap ...

Generating a bullet list from an array of objects

Looking to create an unordered list with vanilla JS, using an array of objects to populate the list. Struggling a bit on how to accomplish this. Here is my current code: let myObj = [ {name: "Harry Potter", author: "JK Rowling"}, {name: "Hunger Gam ...

Add a button to the MCE toolbar without replacing it (Plugins)

One challenge I encountered was integrating the textcolor plugin into tinyMCE. Although I managed to make it functional, I faced an issue with the toolbar configuration. I couldn't grasp how to include the plugin buttons without replacing the existing ...

Utilizing various directives with distinct scopes for a single element

Is it possible for an element to have multiple directives with their own unique scopes? For example, let's consider a custom directive's child element with the controller's scope along with another directive (such as "ng-class"): <custo ...

The error thrown is: "Attempting to access the 'authService' property of an undefined object using TypeDi."

In the process of setting up an authentication system, I have created a class called AuthRouter: import { Router } from 'express' import Container, { Service } from 'typedi' import AuthenticationController from './index' @Ser ...

Issue with the functionality of a checkbox input placed inside a label

I successfully created a functioning checkbox: <div class="custom-control custom-switch mt-3 ml-4"> <input type="checkbox" class="custom-control-input" id='G1'> <label class="custom-cont ...

effective ways to extract objects from nested structures using a specific identifier

In this sample data, I am looking to filter an object based on its ID key let myData = { "nodeInfo": { "9": { "1": { "ID": "14835" ...

The IDs and classes of HTML elements

I have two different implementations of a livechat script. On my sandbox site, the livechat is fixed to the bottom right of the page and scrolls with the window. However, on my live site (where this specific code comes from), it is attached to the footer. ...

Warning: npm has detected conflicting global and local configurations in your settings

Could you please explain what is causing this problem and how can it be addressed during the initial installation? ...

Error: The middleware function is not recognized | Guide to Transitioning to React Redux Firebase v3

After utilizing these packages for my project, I encountered an error in middleware composition while creating a new react app with create-react-app. Below are the packages I have included. Can someone please help me identify what is missing here? HELP I ...

Is it possible to execute a script from a different directory?

Currently, I am developing a nodejs package that involves executing a bash script within the program. The specific bash script, "./helpers/script.sh", needs to be run using a relative path. This means that when users install and run the package, the script ...

Chrome experiencing problems with placeholder text fallback event

My text field has a placeholder text that says "First Name". When the user clicks on the field, the text disappears and allows them to type in their own text. HTML <input class="fname" type="text" placeholder="First Name"/> JS function handlePlac ...

Changing the size of various types of images

Is there a way in JavaScript to automatically resize and fill in a block with fixed width using different images with various dimensions? I came across something similar, but it was in AS2. I'm unsure if it can be translated to JavaScript. var _loc3 ...

How can I alter the icon's color?

Is it possible for the icon's color to change to red when the condition is greater than 0, and to gray when the condition is equal to zero? <TouchableOpacity onPress={() => { if (Object.values(selectedIt ...

There seems to be an issue with the owlCarousel as it is not functioning correctly - it appears to be stuck and unresponsive,

The carousel appears to be stuck and not moving, despite being properly initialized with the correct libraries. Pressing the buttons also does not trigger any movement. I have verified that I am using the latest versions of owlCarousel and jQuery library ...

Divide text to reduce its width within the confines of a specific height on a div element

I've spent the past week scouring various forums, including stackoverflow, but I haven't been able to find a solution. In my responsive website, I'm using CSS flexbox to display dynamic menu items. Sometimes the text can be quite long, and ...

Event firing in child components of Vue.js can occasionally fail to trigger

When using component A to render multiple instances of component B using v-for, an animationend event is fired from component B to A. However, there are cases where the animationend event fails to fire. View the code sandbox for more information ...

Why isn't my AJAX post in Rails working with a partial JS.slim template?

I'm working on a Rails application similar to a comments board and I want to incorporate ajax functionality. However, my code is not functioning as expected and I can't seem to pinpoint the issue... Here is the code from my controller: # contro ...