Article

Form Validation on the Client Side

Page: 1 2

Ok, that was pretty good, but don't you feel that it's a little too much code for every field? What if we create a simple library of functions that can save lots of typing and download time for the page? Well, next we'll do exactly this -- and we'll define our basic functions, to make the validation code even shorter.

function validateNumber(field, msg, min, max) {  
if (!min) { min = 0 }  
if (!max) { max = 255 }  
 
if ( (parseInt(field.value) != field.value) ||  
       field.value.length < min || field.value.length > max) {  
alert(msg);  
field.focus();  
field.select();  
return false;  
}  
 
return true;  
}

This function performs the simple validation of a number -- it checks whether the field contains digits only, and optionally, if it is within a given range. You'll note that this code passes the error message as a parameter. To use such a function, we can basically add it to the onsubmit handler, like so:

<form action="handler"  
onsubmit="return validateNumber(this.phone,  
'Please enter a phone number, numbers only', 5, 10);">

Called like this, it will check whether the phone number is numeric, and is more than 5, but less than 10 digits long. Note how the phone object is passed as a parameter? This allows us to focus upon it via the helper function, as opposed to passing the value of the field only.

Another method for validating numbers is to require them to be within a given range. To make the function do this kind of validation, simply change the check line to:

if ((parseInt(field.value) != field.value) ||  
field.value < min || field.value > max) {

If you want to apply more than one check to the form, you can embed several rules in the onsubmit handler. Imagine, for example, that we require first and last name to be entered, in addition to the phone number:

<form action="handler"  
onsubmit="return (  
validateNumber(this.phone, 'Please enter a phone  
       number, numbers only', 5, 10) &&  
validateString(this.firstName, 'Please  
       enter your first name', 3, 15) &&  
validateString(this.lastName, 'Please  
       enter your last name', 3, 15)  
);">

The code requires all validation rules to evaluate to true (with the logical AND - &&). A closer look reveals that it's very easy to generate this kind of code from a server scripting language... but that's a whole other article.

function validateString(field, msg, min, max) {  
if (!min) { min = 1 }  
if (!max) { max = 65535 }  
 
if (!field.value || field.value.length < min ||  
field.value.max > max) {  
alert(msg);  
field.focus();  
field.select();  
return false;  
}  
 
return true;  
}

As you can see, the string validation function looks more or less the same; you can also write other functions and combine them with these.

A common field required in many forms on the Web is the user's email address. I've seen a lot of functions to do this, but usually the simplest and easiest way to validate an email address is to use regular expressions.

Now we'll extend our function, making it possible to define the field as optional.

function validateEmail(email, msg, optional) {  
if (!email.value && optional) {  
return true;  
}  
 
var re_mail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+  
       ([a-zA-Z])+$/;  
if (!re_mail.test(email.value)) {  
alert(msg);  
email.focus();  
email.select();  
return false;  
}  
 
return true;  
}

To validate a required email you should call it as:

validateEmail(this.email, 'Please enter your email address')

and if you want it to be optional:

validateEmail(this.email, 'Please enter a correct  
email address or leave the field blank', true)

JavaScript cannot be used on its own for validation, but it helps a lot if you have it. The more compact the code you embed into your HTML, the better -- it saves download time, and search engines will like you for it!

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links

Rate This Article

  • 1
    Poor
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
    Great

Comment on This Article

Have something to say?

Post A Comment

You need to be a member of the SitePoint Forums to comment on this post. Sign Up

Already a member? Post using your SitePoint Forums account: