You are currently viewing 3 Simple Methods to Check Email Valid in Javascript

3 Simple Methods to Check Email Valid in Javascript

Check Email Valid JavaScript

Email validation is an important aspect of web development as it ensures that users enter valid email addresses. We can check the email validation using JavaScript. JavaScript provides several built-in methods that allow to check whether an email address is valid or not.

What is valid E-mail?

If the email address contains username, ‘@’ symbol and domain name correctly then it is a valid email. Username can contain letters, numbers, underscores and it must be placed first in email address. The symbol ‘@’ is placed between the username and domainname. Domain name consists of a server name and a top-level domain, separated by a dot, for ex: “email.com”.

For example, a valid email address : “exampleName@gmail.com“, where “exampleName” is the username and “email.com” is the domain name. ‘@‘ symbol is placed correctly. It should be noted that the domain name must be registered and actively accepting emails for the email address to be considered valid.

3 Ways to check email valid

1.Regular expression method:

We can check the email has a valid format using regular expression, with the correct number of characters before and after the “@” symbol and a valid domain name. The regular expression ^[^\s@]+@[^\s@]+\.[^\s@]+$ means:

  • ^ = start of the string
  •  [^\s@]+ = any character that is not whitespace or “@”, one or more times
  • @ = the “@” symbol
  •  [^\s@]+ =  any character that is not whitespace or “@”, one or more times
  • \.  = a literal “.” character (escaped with a backslash)
  • [^\s@]+ = any character that is not whitespace or “@”, one or more times
  • $ = end of the string
READ ALSO  What is this Keyword in JavaScript With Example

Ex:

function isValidEmail(email) {
 return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

document.write(isValidEmail('Example@gmail.com')); // true
document.write(isValidEmail('Examplegmail.com')); //false
  1. This function ‘isValidEmail’ has a parameter ’email’.
  2. Then function returned the valid email or not using regular expression.
  3. If the email is valid, it returns ‘true’ otherwise it returns ‘false’.

2. Email validation library:

In this method, you’ll need to install the email validation library using a package manager like npm. Running the following command in your terminal to install it:

npm install email-validator

After installed the package, you can use it in your JavaScript code like this:

const validator = require('email-validator');

// check if an email is valid
const email = 'example@email.com';
const isValid = validator.validate(email);

if (isValid) {
 console.log(`${email} is a valid.`);
} else {
 console.log(`${email} is NOT a valid.`);
}

//Output: example@email.com is a valid.
  1. In this example, we have created constant ‘validator’ and intialized the package ’email-validator.
  2. We have initialized the email we are going to check in the constant ’email’. Then we create another constant ‘isValid’ and initialize ’email’ in the validate() method of the validator package.
  3. Then we set the condition, If the constant ‘isValid’ returns true, the given email is valid else the given email is not valid.

3. HTML5 email validation:

We can use HTML5’s built-in email validation by set the ‘type’ attribute of an input field to ’email’, like this:

HTML:

<label for="email">Email:</label>
<input type="email" id="email" name="email">

If the user enters an invalid email address, the browser will display an error message telling the user to enter a valid email address.

We can also use JavaScript to access the validity state of the input element. And we can perform custom actions based on whether the input is valid or not. Here’s an example:

<!DOCTYPE html>
<html>
<head>
   <title>Email Validation</title>
</head>
<body>
   <label for="email">Email:</label>
   <input type="email" id="email" name="email">
   <span id="email-validation"></span>

<script>
  const emailInput = document.getElementById('email');
  const validationMessage = document.getElementById('email-validation');

  emailInput.addEventListener('input', () => {
    if (emailInput.validity.valid) {
      validationMessage.textContent = 'Valid email address';
    } else {
      validationMessage.textContent = 'Invalid email address';
    }
  });
</script>

</body>
</html>
  1. In this code, we have created a <label> tag and set ‘for’ attribute to ’email’ to display text. Then we created <input> and set ‘type’ & ‘id’ attribute to ’email’ to get input from user. And we created <span> tag and set the ‘id’ attribute to ’email-validation’
  2. Then we selecting the ’email’ input element using its ID (“email”) and storing it in the ’emailInput’ constant. Simarly, we selects the empty span element using its ID (“email-validation”) and stores it in the ‘validationMessage’ constant.
  3. Then we adds an event listener to the email ‘input’ element, which listens for the ‘input’ even.
  4. Then we check whether the ‘validity.valid property’ of the email input element is’true’ or ‘false’. If ‘true’, the code sets the text content of the ‘validationMessage’ element to “Valid email address” using validationMessage.textContent = ‘Valid email address’;. If ‘false’, the code sets the text content of the validationMessage element to “Invalid email address”.

Leave a Reply