Most of the HTML forms which collects the user data contains an email field. It is a good practice to properly validate those fields in the form before sending it to the server.
The following example shows you how to validate an email field.
Example
- If it is a valid email, the color of the email field will be green.
- If it is an invalid email, the color of the email field will be red.
Source code
JavaScript
function msValidateEmail(mail)
{
if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/.test(mail.value))
{
mail.style.color="green";
}
else
{
mail.style.color="red";
}
}
HTML Markup
<input type="text" class="form-control" id="mstxtemail" onkeyup="msValidateEmail(this);" placeholder="Enter an email id">
Try it yourself
See the Pen Email id validation using JavaScript by Mishel Shaji (@mishelshaji) on CodePen.