javascript
Regex for email validation in Javascript
The best way to validate an email address using javascript is by using regular expressions and check it against the email.
function email_validator(my_email) {
var email_pattern = /^(([^<>()[]\.,;: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,}))$/;
if (email_pattern.test(my_email)) {
console.log("Email is Valid");
} else {
console.log("Email is Invalid");
}
}
email_validator("[email protected]"); // -> logs - Email is Valid
email_validator("test.com"); // -> logs - Email is Invalid
In the code example, we are validating two emails using the email_validator() function which is using regular expressions to validate the email address. If the email is valid it will log "Email is valid" and for an invalid email address, it will log "Email is Invalid".
LIVE DEMO
Was this helpful?
Similar Posts
- Email Validation on Field Redux Form
- Get text before @ in an email using Javascript
- Validate a url using regex in Javascript
- Using regex to validate a phone number in Javascript
- Apply required field validation on redux form fields
- Apply multiple validation on same field redux form
- Enter only number field validation redux form