Home >Web Front-end >JS Tutorial >How Can I Validate Email Addresses Using JavaScript Regular Expressions?
Email Validation with Regular Expressions in JavaScript
To prevent erroneous user input, JavaScript allows for the validation of email addresses before attempting to send them to a server or attempting to send an email to them.
The most reliable approach for verifying an email address in JavaScript is to use regular expressions. The following regular expression accepts ASCII characters:
const validateEmail = (email) => { return String(email) .toLowerCase() .match( /^(([^<>()[\]\.,;:\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,}))$/ ); };
For unicode support, a more comprehensive regex can be used:
const re = /^(([^<>()[\]\.,;:\s@"]+(\.[^<>()[\]\.,;:\s@"]+)*)|(".+"))@(([^<>()[\]\.,;:\s@"]+\.)+[^<>()[\]\.,;:\s@"]{2,})$/i;
However, it's crucial to remember that JavaScript validation shouldn't be depended on alone. Client-side validation is easily bypassed. Server-side validation is also necessary.
Here's an example of JavaScript email validation on the client side:
const validateEmail = (email) => { return email.match( /^(([^<>()[\]\.,;:\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,}))$/ ); }; const validate = () => { const $result = $('#result'); const email = $('#email').val(); $result.text(''); if(validateEmail(email)){ $result.text(email + ' is valid.'); $result.css('color', 'green'); } else{ $result.text(email + ' is invalid.'); $result.css('color', 'red'); } return false; } $('#email').on('input', validate);
In this example, a button is used to trigger the validation and display the result.
The above is the detailed content of How Can I Validate Email Addresses Using JavaScript Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!