How to validate an email address in JavaScript
In almost all cases, it is advisable to validate the user input for various reasons (security, reliability, etc.). In this tutorial, we will learn how to write a script that can be applied for the validation of the e-mail address in Javascript.
Program to validate an email address in JavaScript
<html> <head> <script> function checkEmail(email) { var re = /^(([^<>()[\]\\.,;:\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,}))$/; return re.test(email); } function validate() { var email = document.getElementById("email").value; if (checkEmail(email)) { alert('Valid email address'); } else { alert('Email address Invalid'); } return false; } </script> </head> <body> <p>Enter an email address:</p> <input id='email'> <button type='submit' onclick="validate()">Validate!</button> </body> </html>
Result |
---|
Enter an email address: |