How to Validate an Email Address in JavaScript
Validating user input as an email address is crucial to prevent errors when sending data to servers or emails. JavaScript offers a convenient method for email address validation using regular expressions.
Regular expressions provide a powerful way to match and validate email addresses. A commonly used regular expression is:
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,}))$/ ); };
This expression matches email addresses that adhere to the following criteria:
While relying on client-side validation alone is not recommended due to the possibility of JavaScript being disabled, it can provide a first line of defense. Here's an example of validating email addresses using JavaScript:
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,}))$/ ); };
This validation function can then be used in a form or on user input fields to provide instant feedback on email address validity.
The above is the detailed content of How to Validate Email Addresses Using JavaScript Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!