To validate email in JavaScript, we can use regular expression .test()
method.
In below code snippet, we have a text box and a button. Clicking on button calls Validate() function that in tern call ValidateEmail function.
ValidateEmail function uses regular expression to test the value of the text box and returns true or false. Here re is the regular expression used to check for the format of the email.
<p>Validate Email in JavaScript</p>
<input type="text" id="email" />
<button onclick="Validate()">Validate Email</button>
<script>
function Validate(){
var mail = document.getElementById("email").value;
alert(ValidateEmail(mail));
}
function ValidateEmail(mail) {
var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(mail);
}
</script>
The output would be an alert showing "true" if valid email entered into text box otherwise "false".
Views: 5315 | Post Order: 81