Hello friends, If you are new to web development, you are at the right place to learn a lot of basic stuffs needed to be known. Today in this post I’m writing a very basic validation of a Web form using JavaScript.
This Basic JavaScript form validation covers the below,
1. How to validate a form before submit it.
2. How to get value of a input using it’s attribute id.
3. How to check if a input field is empty (only basic)
Here is the entire Basic JavaScript Validation script with HTML Form:
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 |
<html> <head> <title>Basic JavaScript Form Validation - Tutorialsmade.com</title> <script> //JavaScript custom function to validate the form values function validateForm(){ //get value of the each form field by respective id var name = document.getElementById('name').value; var username = document.getElementById('username').value; var password = document.getElementById('password').value; var address = document.getElementById('address').value; //check all the fields are not empty, if then alert if( name == '' && username == '' && password == '' && address == ''){ alert("Please enter all the fields"); return false; } //check individual fields are not empty, if then alert respectively if(name == ''){ alert("Please enter name"); return false; } if(username == ''){ alert("Please enter username"); return false; } if(password == ''){ alert("Please enter password"); return false; } if(address == ''){ alert("Please enter address"); return false; } //if no errors found, return true, so the form can be submitted. alert("Cool, all the fields are fine, lets Submit the form"); return true; } </script> </head> <body> <h3>Basic JavaScript Form Validation - <a href=""> Tutorialsmade.com</a></h3> <!-- onsubmit attribute is used to call the validatForm() JavaScript function --> <!-- if the function return false, then the form won't submit --> <form action="" method="post" onsubmit="return validateForm()"> <p>Name: <input type="text" id="name" /></p> <p>Username: <input type="text" id="username" /></p> <p>Password: <input type="password" id="password" /></p> <p>Address: <textarea id="address"></textarea></p> <p><input type="submit" name="submit" /></p> </form> </body> </html> |
Read the comments in the above script to understand it.
ValidateForm() is the custom JavaScript function.
Onsubmit attribute helps to execute a JavaScript Function before submitting the form, if the JavaScript function returns false, then the form will not be submitted .
Here is the demo of the above script to test it online: