In today’s post i will explain to how to validate a form using javasrcipt. This is very easy & simple javasrcipt code to validate text box. JavaScript can be used to validate data in HTML forms before sending the data to web server.
Below function check if form text box is blank .If the text box is left blank, an alerts message is display as popup on the web pages, and function returns false, and the form will not be submitted:
1 2 3 4 5 6 7 8 9 | function validateForm() { var x=document.getElementById("name").value; if (x==null || x=="") { alert("Please enter the name."); return false; } } |
Add below HTML code after body tag. In the below i have added a javascript function validateForm()
and define the same function in above javascript code which will get the text box value and validate according to define rules.
1 2 3 4 5 | <form name="contact" action="demo.php" onsubmit="return validateForm()" method="post"> First name: <input type="text" id="name" name="name"> <input type="submit" name="submit" value="Submit"> </form> |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.
Article Tags: javascript code text box validation, Javasrcipt, Jquery, jquery tutorials for beginners, jquery validations, text box validation using javascript, textbox validation example