In this tutorial we are validating HTML forms with JavaScript. This JavaScript tutorial is only about client side form validation.
Handling and validating forms in JavaScript is quite easy. We are going to validate a simple HTML form via JavaScript from client side only. Make sure to re-validate the form through server side too as we can’t relay only on client side validation – validating forms on client side is just for better user friendliness.
Required Files Handling and Validating Forms
simple_form.html
<html> <head> <title>Simple HTML Form Validation</title> <script type="text/javascript" src="form.js"></script> </head> <body> <form action="simple_form.html" method="get" id="reg_form"> Name: <input type="text" name="name" id="name"/><br /> Email: <input type="text" name="email" id="email"/><br /> Phone: <input type="text" name="phone" id="phone"/><br /> Password: <input type="password" name="password" id="password"/><br /> Confirm Password: <input type="password" name="confirm_password" id="confirm_password"/><br /> <input type="submit" name="submit" value="Register" /> </form> <p>note: Name and passwords 3 to 20 chars long, email must be valid and phone must be 10 digits numeric.</p> </body> </html>
Now, to validating forms, we’ll use the following JavaScript.
form.js
window.onload = function () { // calling a stanalone function on window.onload event var allok = true; // initializing allok as true // getting particular form then onsubmit calling a standalone function document.getElementsByTagName("form")[0].onsubmit = function () { // taking and storing each inputs after submit var name = document.getElementById("name").value; var email = document.getElementById("email").value; var phone = document.getElementById("phone").value; var password = document.getElementById("password").value; var confirm_password = document.getElementById("confirm_password").value; var error = ""; // initializing error as blank // validating forms start here if (name.length <= 3 || name.length >= 20) { error += "\n\rInvalid Name."; allok = false; } if (checkEmail(email) == false) { error += "\n\rInvalid Email."; allok = false; } if (isNaN(phone) || phone.length > 10 || phone.length < 8) { error += "\n\rInvalid Phone."; allok = false; } if (password.length <= 3 || password.length >= 20) { error += "\n\rInvalid Password."; allok = false; } if (password != confirm_password) { error += "\n\rConfirm password did not matched.."; allok = false; } // if allok is false, prevent submitting the form if (allok == false) { alert(error); return false; } } function checkEmail(inputvalue){ // cheching for invalid email var pattern=/^([a-zA-Z0-9_.-])[email protected]([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/; if(pattern.test(inputvalue)) return true; else return false; } }
Having problems with validating forms? Need help? Just comment below, I’ll be back to you.
Thank you!