How to Validate a HTML Form Using JavaScript?

In the previous post, I have described about "How to create a simple form using HTML" step by step with describing what is a form and what elements are used to create HTML form along with complete HTML code for a form. In this post I am going to describe about to Validate a this HTML Form Using JavaScript.

You can validate a HTML Form Using JavaScript for the following circumstances.

  • Whether or not the user left required fields empty
  • Whether or not the user entered a valid e-mail address
  • Whether or not the user entered a valid date
  • Whether or not the user entered text in numeric field or entered number in text field

Here in this post I am going to describe you, "How to Validate Required Fields using JavaScript.

Validating Required Field using JavaScript


This JavaScript Function below checks if a required field has been left empty. If the required field is blank, an alert box alerts a message and the function returns false. If the value is entered the function returns true.

function validate_required(field, alerttxt)
{
with(field)
{
if (value===null||value==="")
{alert(alerttxt); return false;}
else {return true;}
}
}

Complete JavaScript Code with HTML for Validating Required Field


Here are the complete JavaScript codes along with complete HTML codes uses with the JavaScript Functions given below.


Subscription Form




First Name:


Last Name:


Password:


Retype Password:


Email:










Preview of the above HTML Code



First Name:

Last Name:

Password:

Retype Password:

Email: