Validate email address using javascript
- 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:
- <!DOCTYPE html>
- <html>
- <head>
- <script>
- function validateEmailForm() {
- var x = document.forms["Form_Name"]["txt_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="Form_Name" action="User_email_validation.jsp" onsubmit="return
- validateEmailForm();" method="post">
- Email: <input type="text" name="txt_email">
- <input type="submit" value="Submit">
- </form>
- </body>
- </html>
Validate email in java-script using regular expression: on submit form validation
- <!DOCTYPE html>
- <html>
- <head>
- <script>
- function validateEmailForm() {
- var email = document.forms["Form_Name"]["txt_email"].value;
- var re = /\S+@\S+\.\S+/;
- return re.test(email);
- }
- }
- </script>
- </head>
- <body>
- <form name="Form_Name" action="User_email_validation.jsp" onsubmit="return
- validateEmailForm();" method="post">
- Email: <input type="text" name="txt_email">
- <input type="submit" value="Submit">
- </form>
- </body>
- </html>
HTML 5 Email validation:
- <form>
- <input type="email" placeholder="Enter your email">
- <input type="submit" value="Submit">
- </form>