Friday , 22 March 2019
Home / Programming / JavaScript / Basic Form Validation – JavaScript Tutorial
Basic Form Validation
Basic Form Validation

Basic Form Validation – JavaScript Tutorial

This tutorial is part of the JavaScript tutorial series for beginners. To view the whole list of tutorials available and the order in which you should follow them, then click here.

Today, we’ll be talking about basic form validation. This tutorial series so far has 2 main segments which are what and why. The first part, what, covers the basics of JavaScript. I taught you what variables, functions, loops, conditional statements, and events are. Now, you’re more than ready to start creating dynamic websites. However, you may be confused by the purpose of each topic I taught. You may understand why you might need one thing, but not another.

These next couple of tutorials will start teaching you why you use certain aspects of programming. You know what each thing does, but why use it? We’re going tackle 3 real world projects. They’ll be very basic, but usable. If you need it to be more advanced, then it’ll be up to you to customize it.

Not everything you ever do will be covered in a tutorial. It’s good practice to become self dependent. Another benefit to this part of the tutorial series is to start thinking like a programmer. You’ll be able to tackle big projects and learn how to break them up into small parts.

Getting Started

Whenever you start a project, big or small, you should always think about what you’ll need to generally do. For this tutorial, we’ll be validating a form. So, what do you think you’ll need to do to validate a form in JavaScript? Well, here’s what I’ve come up with. Clear your script and add this bit of code into it.

You’ll notice this is just one huge block comment with steps of what we’ll need to do. You won’t be able to write down every single step because there are always things you won’t be able to account for. You may end up adding extra steps. You may end up running into a problem. These steps are just a general way to do things and what you believe you have to do. Trust me when I say this, you will save a lot of time by creating steps ahead of time.

You usually won’t see steps when you view other developer’s code. After this project is over, you can delete these steps as you won’t need them anymore. Sometimes, if you ever work for a client, you’ll get a document instead of comments in a code for what you have to do.

Setting up our Document

Now, we’ll set up some things in our document. So far, our document has been pretty simple. Let’s change this and make a form. Update the body tags in your document to this.

With this bit of code, we just did the first 2 steps. We created a form. This form has 2 text fields, 1 drop down, 2 radio buttons, 1 check box and 1 submit button. It is VERY important you give each of your form fields a name. The only time you don’t need to do this is for your option tags in your drop down box. The select tags, however, need a name. Your form as well needs a name. You should be familiar with how to create forms.

Next, on top of our form, you’ll notice we have a <div> with the id of message. Right now, it’s empty. We’ll be dynamically adding an error message if the user fills in the form incorrectly.

Right now, the error message is the same text color as everything else. We want to make it clear that this is an error message. Let’s add some CSS to do this.

Add this small bit of CSS code in your header tags.

All this does is change the error message’s text color to red.

Setting up the Script

Add this bit of code into your script.

Two things are going on here. First, we’re using the HTML DOM to have access to our div tag that will contain the error message. Next, we use the HTML DOM to grab our form. To grab a form, you simply type in the name you gave it in the HTML document. There are actually a couple of ways to grab a form. Another way of grabbing a form is like this.

You don’t have to add this to you script. All forms are stored in an array called forms that are apart of the document object. This array will contain all forms currently in the HTML document. To access a certain form, you enter the name of the form or the index of the form. The shorter and simpler way is just to type in the name like we did in the first bit of code.

Capturing the Submit Event

We are now on step 5. We must capture the moment the form is submitted. Now, you may be thinking you would use the onclick event, but there’s another event that was specifically made to capture the moment the form is submitted. Add this bit of code into your script.

The onsubmit event will run when a form is submitted. We want to make sure it only runs when our example form is submitted. Right now, our form will submit even if there’s an error. To prevent a form from submitting, then you must return false. Add this bit of code inside our anonymous function.

If you refresh your page and try submitting your form, then nothing will happen. If our form was to submit and there was an error, then we wouldn’t know because the page would have been refreshed. This will temporarily allow us to catch any and all errors.

Next, inside your anonymous function, add this bit of code. This bit of code should be placed before the return statement. This is because all code after a return statement is NOT executed. So, the return statement should be the last line of code inside your anonymous function.

This will simply contain the error message. Now, you may be thinking, why do we have 2 variables  containing error messages? Well, the first variable gives you access to the HTML element. The 2nd variable will contain the string of the error message. You’ll see what I mean soon.

We’re currently on step 8. We need to grab the values inside the form when it’s submitted. So, add this bit of code into your anonymous function.

Our variable, exForm, contains our form. We can use this variable to access the input fields in our form. To get a certain field inside our form, you simply use the name from the name attribute of the field. Next, to grab the value inputted, you access the value property. We store these values in variables. For our first 3 variables, we get the values of the name, zip code, and drop down.

The next 2 variables are a special case. Since, there can be multiple radio buttons,but only one can be checked in a group, then you must loop through each one to check which one is checked. However, check boxes are a different case. The checked property is either true of false if the check box is checked.  You’ll see in a moment how this plays out.

Validating the Fields

Add this bit of code next.

We use the power of conditional statements to check each field. All these if statements are separate so they all run checks regardless if one is true or not.

The first and third conditional statements check if the values are simply empty. If they are, then we append a string stating to please fill or select a value. The second conditional statement does the same thing, but it also does one more check. The isNaN() function will check if a value is a number or not. NaN stands for Not-a-Number. This function is an in-built JavaScript function and will return true if our zip code is not a number.

Next add this bit of code.

The validateRadio() function is not a built-in function in JavaScript. So, we have to create one for ourselves. The reason we’re creating this function instead of running this code inside our anonymous function is because checking for radio button checks is a common task. So, it would make sense to make this into a function. Outside of the onsubmit event, add this bit of code.

This function has 1 parameter which is the group of radio buttons to check.  We, then loop through each radio button to check if any of them are checked. Remember, that the variable radio contains the index not the value. So, we have to check the array sent in and use the variable, radio, as our index. We, then have to access the property checked to see if that is true or false. Our return statement inside our loop will only execute if our condition is true. If not, then the other return statement will return false.

Inside our anonymous function, you’ll notice a ! before our function. This exclamation point is asking for the complete opposite of the function. If the function returns false,  then our if statement will run. This is one way to do things.

Let’s finish this up with this bit of code inside your anonymous function.

Unlike our radio buttons, check boxes, you don’t have to loop through each one. You can check each one individually.  The last if statement will check if our errorMessage variable is empty. If it is, then that means everything was validated and you can finally submit the form. If not, then update the div tag with the full error message. You’ll notice we moved our return statement inside this conditional statement.

That’s it! You can now refresh your page and try submitting the form fully empty, partially empty, or filled in correctly.


This basic form validation will protect you from basic hacks. It is HIGHLY recommended you perform some more validation with server side programming languages like PHP or ASP. Client side JavaScript will only protect you so far.If you need to make more customizations, then go for it. You should now have a basic understanding of JavaScript applications. If you’ve made any errors, then please compare your code to mine. All code is available to download on my site :)!

About Jasko Koyn

Check Also


Audio – Advanced JavaScript Tutorial

The video and audio objects both have the same events, properties and methods. So, you …

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.