How to format and validate email node js How to format and validate email node js express express

How to format and validate email node js


Use regular expression something like that:

Solution 1:

^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$

Sample code:

const emailToValidate = 'a@a.com';const emailRegexp = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;console.log(emailRegexp.test(emailToValidate));

Solution 2:

Because you use angular, you are able to validate the email on front-end side by using Validators.email.

If you check angular source code of Validators.email here, you will find an EMAIL_REGEXP const variable with the following value:

/^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;

You could use it on back-end side too, to validate the input.


You can use email validator module:

var validator = require("email-validator");validator.validate("test@email.com");

Or, if you don't want any dependencies:

var emailRegex = /^[-!#$%&'*+\/0-9=?A-Z^_a-z{|}~](\.?[-!#$%&'*+\/0-9=?A-Z^_a-z`{|}~])*@[a-zA-Z0-9](-*\.?[a-zA-Z0-9])*\.[a-zA-Z](-?[a-zA-Z0-9])+$/;function isEmailValid(email) {    if (!email)        return false;    if(email.length>254)        return false;    var valid = emailRegex.test(email);    if(!valid)        return false;    // Further checking of some things regex can't handle    var parts = email.split("@");    if(parts[0].length>64)        return false;    var domainParts = parts[1].split(".");    if(domainParts.some(function(part) { return part.length>63; }))        return false;    return true;}

Source:

https://www.npmjs.com/package/email-validator

https://github.com/manishsaraan/email-validator/blob/master/index.js