Js email validation
Here are some examples of JavaScript email validation:
Simple Email Validation
function validateEmail(email) {
var re = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
return re.test(email);
}
This regular expression matches most common email formats, but it's not foolproof. It allows for letters, numbers, dot (.), hyphen (-), underscore (_), and plus sign (+) in the local part, and requires a top-level domain (TLD) with at least 2 characters.
More Advanced Email Validation
function validateEmail(email) {
var re = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
var localPart = email.substring(0, email.indexOf('@'));
var domain = email.substring(email.indexOf('@') + 1);
if (localPart.length > 64) return false;
if (domain.length > 253) return false;
if (!re.test(email)) return false;
return true;
}
This version of the function also checks the length of the local part and domain, which are limited by the RFC 5322 standard.
Using a Library
const emailValidator = require('email-validator');
function validateEmail(email) {
return emailValidator.validate(email);
}
This uses the email-validator
library, which provides a more comprehensive and accurate email validation.
Example Usage
var email = '[email protected]';
if (validateEmail(email)) {
console.log('Email is valid');
} else {
console.log('Email is not valid');
}
Note that email validation is not foolproof, and it's always a good idea to use a combination of validation and other security measures to ensure the security of your application.