Validate Html Form in JavaScript Example

Updated on     Kisan Patel

This tutorial will show you how to validating the html form using JavaScript.

Validating the HTML form is the matter of finding the control and checking for the required data.

<form action="" method="post">
   <p>First Name: <input type="text" id="txtFirstName" name="txtName" /> *</p>
   <p>Last Name: <input type="text" id="txtLastName" name="txtName" /></p>
   <p>Email: <input type="text" id="txtEmail" name="txtEmail" /> *</p>
   <input type="submit" id="btnSubmit" value="Submit" onclick="return ValidateTheForm()" />

<script type="text/javascript" language="javascript">
function ValidateTheForm() {
   if(document.getElementById("txtFirstName").value == '') {
       alert("Please specify first name, it is mandatory !");
       return false;
   if(document.getElementById("txtEmail").value == '') {
       alert("Please specify email, it is mandatory !");
       return false;

In the above code snippet, we have three textboxes (txtFirstName, txtLastName, txtEmail) and a Submit button that fires ValidateTheForm() function.

In this example, I am 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.

See the Pen mJozYa by Kisan (@pka246) on CodePen.


Leave a Reply