Email Validation in Html Form using Javascript

If you are designing a form in HTML. During. Validation of Email very important while validating an HTML form. In this blog, I have written a simple javascript code for email validation.

First Know about each email

  • Email is a String
  • Every email contains two common characters.
  1.  dot (.)  i.e.   amansibg44@outlook.com
  2.   at (@) i. e.   donalju9@gmail.com

 

During Validation, we have to check is there both dot(.) and at(@) are in an email or not.

Code

<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
var x = document.forms[“myForm”][“email”].value;
var atpos = x.indexOf(“@”);
var dotpos = x.lastIndexOf(“.”);
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
alert(“Not a valid e-mail address”);
return false;
}
}
</script>
</head>

<body>
<form name=”myForm” action=”/action_page_post.php” onsubmit=”return validateForm();” method=”post”>
Email: <input type=”text” name=”email”>
<input type=”submit” value=”Submit”>
</form>
</body>

</html>

 

This above code perfectly running in the browser.

Leave a Reply

Your email address will not be published. Required fields are marked *