How To Validate HTML Form Using JavaScript

In the previous post, I have written about HTML forms. So you know how to create an HTML form but do you know how to validate it? Validation basically means to check if the the form information is valid.

One of the example would be to check if the user has left a required field empty. If he has left the field empty then the user shouldn’t be allowed to submit the form. If the user submits the form by keeping a required field empty then we’ll alert the user with a message and shift the user’s focus or cursor to the empty field.

Suppose we have a simple form which asks the user to enter the first name and last name. The code for the same is given below. We have added the submit button here using the input tag with type as submit.

I assume you don’t need any explanation for the HTML code. Once we have the HTML form ready we’ll create the JavaScript function. Given below is the code for JavaScript function which we’ll use to validate the given form.

We have written JavaScript code inside the script tags. The code contains a JavaScript function called validateForm(). Inside this function we have two parts. First part is for fname and the second part is for lname.

In the first part we created a variable x. This variable x points to document > yoform > fname. Then we check if value of x is null or an empty string. If its null or empty then we’ll alert the user by a message and then move the control or focus of the user to x.

Here x is basically the input field called fname inside yoformwithin the document. (document.yoform.fname). So when user leaves the fname field empty and hits submit, he’ll be alerted and the fname field will be focused upon. The same concept is used for second part.

Putting it together

Use the two codes given above in one single HTML file and you’re good to go. You can find the live form here. Try to submit the form keeping the fields empty and you’ll see how it works.

I hope this was helpful. Thanks for reading and do subscribe to the blog feed for more amazing posts. You can find the subscription box below.