In case we are in the need of validating the html form using JavaScript, we can follow this approach.
Validating the HTML form is the matter of finding the control and checking for the required data.
<script> function ValidateTheForm() { if (document.getElementById("txtFirstName").value == '') { alert("Please specify first name, it is mandatory !"); return false; } else { return true; } } </script> <form action="HTMLPage.htm" method="post"> First Name: <input type="text" id="txtFirstName" name="txtName" /> * Last Name: <input type="text" id="txtLastName" name="txtName" /> <input type="submit" id="btnSubmit" value="Submit" onclick="return ValidateTheForm()" /> </form>
In the above code snippet, we have two textboxes (txtFirstName, txtLastName) and a Submit button that fires ValidateTheForm() function and returns true or false. In this example, we are assuming that FirstName is mandatory field, so in the ValidateTheForm() function we are checking for its value and if it is empty we are showing an alert and returning false. Returning false will prevent the form being submitted to the serer. If the textbox value is not empty we are returning true that will go ahead and submit the form to the server.
OUTPUT
Views: 5465 | Post Order: 59