• One of the famous interview question in JavaScript : how to validate email address in JavaScript.
  • In order to validate a text field of HTML we need a JavaScript function.
  • On submit form we need to call a java script function to validate all fields in the form also known as client side validation.
  • Now on form submit we need to check email text field and validate it whether entered email is in correct format or not for ex: instanceofjava@gmail.com. 



JavaScript program for email validation:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5. function validateEmailForm() {
  6.     var x = document.forms["Form_Name"]["txt_email"].value;
  7.     var atpos = x.indexOf("@");
  8.     var dotpos = x.lastIndexOf(".");
  9.     if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
  10.         alert("Not a valid e-mail address");
  11.         return false;
  12.     }
  13. }
  14. </script>
  15. </head>
  16.  
  17. <body>
  18. <form name="Form_Name" action="User_email_validation.jsp" onsubmit="return
  19. validateEmailForm();" method="post">
  20. Email: <input type="text" name="txt_email">
  21. <input type="submit" value="Submit">
  22. </form>
  23. </body>
  24.  
  25. </html>

Validate email in java-script using regular expression: on submit form validation

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5. function validateEmailForm() {
  6.     var email = document.forms["Form_Name"]["txt_email"].value;
  7.   
  8.  var re = /\S+@\S+\.\S+/;
  9.     return re.test(email);
  10.   
  11.     }
  12. }
  13. </script>
  14. </head>
  15.  
  16. <body>
  17. <form name="Form_Name" action="User_email_validation.jsp" onsubmit="return
  18. validateEmailForm();" method="post">
  19. Email: <input type="text" name="txt_email">
  20. <input type="submit" value="Submit">
  21. </form>
  22. </body>
  23.  
  24. </html>


javascript program for email validation


HTML 5 Email validation:



  1. <form>
  2. <input type="email" placeholder="Enter your email">
  3. <input type="submit" value="Submit">
  4. </form>
email address validation code in java script

Instance Of Java

We will help you in learning.Please leave your comments and suggestions in comment section. if you any doubts please use search box provided right side. Search there for answers thank you.
«
Next
Newer Post
»
Previous
Older Post

No comments

Leave a Reply

Select Menu