JavaScript Form Validation


JavaScript Form Validation

JavaScript can be used to validate the input data in the HTML form before the data is sent to the server.

Form data often needs to use JavaScript to verify its correctness:

  • Is the validation form data empty?

  • Verify that the input is a correct email address?

  • Is the verification date entered correctly?

  • Is the input content of the verification form numeric?


Required Items

The following function is used to check whether the user has filled in the required (or required) items in the form. If the required or required option is empty, then a warning box will pop up, and the return value of the function is false, otherwise the return value of the function is true (meaning there is no problem with the data):

function validateForm()
{
   var x=document.forms["myForm"]["fname"].value;
   if (x==null || x=="")
   {
     alert("Last name must be filled in");
     return false;
   }
}

The above function is called when the form is submitted:

Example

<form name="myForm" action="demo-form.php" onsubmit="return validateForm()" method="post">
    Last name: <input type="text" name="fname">
    <input type="submit" value="Submit">
</form>

Try It! 


Email Verification

The following function checks whether the input data conforms to the basic syntax of an email address.

This means that the input data must contain the @ sign and period (.). At the same time, @ cannot be the first character of the email address, and there must be at least one dot after @:

function validateForm(){
   var x=document.forms["myForm"]["useremail"].value;
   var atpos=x.indexOf("@");
   var dotpos=x.lastIndexOf(".");
   if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length){
     alert("Not a valid e-mail address");
     return false;
   }
}

Here is the complete code together with the HTML form:

Example

<form name="myForm" action="demo-form.php" onsubmit="return validateForm();" method="post">
     Email: <input type="text" name="useremail">
     <input type="submit" value="Submit">
</form>

 Try It!