Sunday, September 22, 2019

JavaScript email validation

We can validate the email by the help of JavaScript.
There are many criteria that need to be follow to validate the email id such as:
  • email id must contain the @ and . character
  • There must be at least one character before and after the @.
  • There must be at least two characters after . (dot).
Let's see the simple example to validate the email field.

  1. <script>  
  2. function validateemail()  
  3. {  
  4. var x=document.myform.email.value;  
  5. var atposition=x.indexOf("@");  
  6. var dotposition=x.lastIndexOf(".");  
  7. if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){  
  8.   alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition);  
  9.   return false;  
  10.   }  
  11. }  
  12. </script>  
  13. <body>  
  14. <form name="myform"  method="post" action="#" onsubmit="return validateemail();">  
  15. Email: <input type="text" name="email"><br/>  
  16.   
  17. <input type="submit" value="register">  
  18. </form>  

No comments:

Post a Comment