Simple Rules for JavaScript Form Validation

Simple Rules for JavaScript Form Validation
Page content

JavaScript in a Nutshell

JavaScript is a powerful and popular scripting language out of the ECMA Script family of scripting languages. JavaScript is ideal for bringing life to static web pages as well as improving the user experience on websites. It is also great for making discreet requests to and from the web server also known as Ajax and JSON.

One thing that we will focus on now is JavaScript’s ability to do web forms validation.

What Should I Validate?

With JavaScript you can validate practically every possible element that can appear on a web form. It is all up to you to decide what you want to ensure is entered correctly by your users. Some elements do need to validated at all times. These include email fields, URL fields, name fields, password fields and fields expecting phone numbers.

The reason why these must be validated is not so much the abuse but to simply ensure that the user does not make careless mistakes or simple typing errors.

Validation Foundation

There are dozens of methods you can choose to validate your forms using JavaScript. Every developer would normally write his code one way while another would write his own code in a different way. Whichever way you choose does not matter. What is important is that your code is well formed and works.

Below I have a block of code that will work with both old and new browsers and is simple enough to use.

Take a form with the following header <form name=”myform” onSubmit=”return validate()”>.

This header gives the form an identifying name and an instruction to call a validation function when the form is submitted.

The base function which will be called should be placed in the HTML header section and would look like this:

function validate(){

with document.myform{

//your validation tests come here

}

return true;

}

The form above simply ensures we are dealing with an element named “myform” in this case a web form, and if all tests pass it returns true. This means it allows the form to be submitted.

Let us now look at a few tests. Please note that all tests are placed in the marked section of the code above.

Checking for Numeric Characters

When you ask a user for a telephone number you expect a few things. That the telephone number is 10 digits long for those in USA and all characters must be numerical digits. There is more we can test for but this will do for demonstration purposes.

So how can we write a test for this assuming our telephone text field in named “phone”? We can use a test that looks like this.

var numberfilter = /D/;

var returnval = numberfilter.test(phone.value);

if( phone.value == ’’ || returnval == false || phone.value.length != 10){

alert(“Please type in a valid phone number.”);

phone.focus();

return false;

}

What the code does here, is, it creates a test for digits and runs the test against the value entered in the phone field keeping the result.This test is based on a regular expression which, formated in the way it is, the Capital “D” tells the code to look for numeric digits and no other form of characters.

Next it checks is the phone field is blank, or if the number of characters is not equal to 10. If any of these tests fail, JavaScript will pass a message to the user asking them to put in a valid phone number. It then puts the cursor in the phone field and returns false; basically it aborts sending the form. If these tests pass then it simple moves on to the next field’s test.

Preventing Empty Fields

Preventing empty fields is just as the test above but with less complexity. Looking at this example for a field called “lastname”.

if(lastname.value == ‘’){

alert(“Please type in your Surname Name.”);

lastname.focus();

return false;

}

Here you can see the structure and flow is similar to the test for the telephone number. Al this does is to make sure the “lastname” field is not blank. The rest is the same as the numerical field.

Simple Password Checks

JavaScripr password validation

Checking for passwords can follow a slightly different rule. You can check the length of a password using the same rule for the phone number. Without having to repeat, you can check that the password entered into a “password” filed matches the “confirm _password” field

if(password && password.value == ‘’){

alert(“Please type in a password.”);

password.focus();

return false;

}

if(confirm_password && confirm_password.value != password.value){

alert(“Your passwords do not match, please correct.”);

password.focus();

confirm_password.value = ‘’;

return false;

}

This test requires a few additional fields. This test first checks that there is a “password” field and it is not blank. If this test fails the user is asked to type in a password. If the user did type in a password the test moves onto the second part of the test which checks that there is a “confirm_password” field and the value in that field is similar to the content in the password field. If this test fails it deletes everything in the “password” field and the user has to type in both passwords a fresh.

The reason why we delete the information in the “password” field is because it is masked and there may have been a typing error.

Well Formed Emails

JavaScript Email Validation

Validating emails and URLs follows similar rules to those of checking for numerical digits. The main difference is that the “email” field uses a more complex regular expression as seen below. The rest of the code follows the same path as all the others above

var emailfilter=/^\w+[\+\.\w-]*@([\w-]+\.)*\w+[\w-]*\.([a-z]{2,5}|\d+)$/i;

var returnval = emailfilter.test(email.value) ;

if(email.value == ’’ || returnval == false){

alert(“Please type in a valid email address.”);

email.focus();

return false;

}

The regular expression looks for combinations of any number of alphanumeric characters with any number of “dots” and a single “@” sign and any number of alphanumeric characters after the “@” sign. Finally it checks for an extension between two and five characters in length.

These are the most common fields that require validation when designing web forms. The important thing to note is that form validations are totally up to the website owner. The general rule is that anything can be validated. Whatever you choose to validate you will probably be using one of the tests listed above in form or slightly modified.

With a little bit of hands-on practice JavaSript form validation will become second nature to the web developer.

References

Sources: