Simple form validation using JavaScript
Here you will learn simple form validation using JavaScript with HTML language.
What is form in html
A Form is a page that includes elements or controls like text fields, check boxes, radio buttons, and submit buttons in HTML. Forms are used to collect information from a user, and provide to the website owners.
Example of Simple form validation using JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 | <!-- form validation using JavaScript with HTML language --> <!DOCTYPE html> <html> <head> <title>Form Validation using JavaScript</title> <style> .error {color: #FF0000;} </style> </head> <body> <!--Form to get the user input --> <h1>Form Validation using JavaScript</h1> <form action="javascript:alert('Form Submitted Successfully...');" method="post" onsubmit="return Validate()" name="vForm"> <p> Name: <input type="text" name="name" id="name" /><br/> <span id="name_error" class="error"></span> </p> <p> Email: <input type="text" name="email" id="email" /><br/> <span id="email_error" class="error"></span> </p> <p> Phone: <input type="text" name="phone" id="phone" /><br/> <span id="phone_error" class="error"></span> </p> <p> <input type="submit" name="submit" value="Submit" /> </p> </form> <script type="text/javascript"> // validate the form using JavaScript function Validate() { var name = document.getElementById("name").value; var email = document.getElementById("email").value; var phone = document.getElementById("phone").value; var name_error = document.getElementById("name_error"); var email_error = document.getElementById("email_error"); var phone_error = document.getElementById("phone_error"); // name validation if (name == "") { name_error.textContent = "Name is required"; return false; } else { name_error.textContent = ""; } // email validation if (email == "") { email_error.textContent = "Email is required"; return false; } else { // email validation if (email.indexOf("@") < 1 || email.lastIndexOf(".") < email.indexOf("@") + 2 || email.lastIndexOf(".") + 2 >= email.length) { email_error.textContent = "Email is not valid"; return false; } else { email_error.textContent = ""; } } // phone validation var phone_regex = /^\(?([0-9]{3})\)?[-.●]?([0-9]{3})[-.●]?([0-9]{4})$/; if (phone == "") { phone_error.textContent = "Phone is required"; return false; } else { // validate format of phone if it is not empty if(phone.match(phone_regex)) { phone_error.textContent = ""; } else { phone_error.textContent = "Phone is not valid"; return false; } } return true; } </script> </body> </html> |
Output
Check out our other JavaScript examples