zomgistania

Main page | About | Articles | Previous Posts | Archives

Friday, August 25, 2006

Form validation with JS

How often do you fill in a form and submit it only to get a page telling you that something was wrong in your input? Yeah, pretty often...

Even though it's very easy to add simple JavaScript validation to the form which tells the user if his input is wrong, almost no form ever has such features.

In this post, I'll introduce some simple means to check the values in forms using JavaScript to provide a better browsing experience to the user.


How does this work?

In the HTML Input element you can have an onChange event and an onKeyUp event (and some others). We can use these to run JavaScript code.

We run a check and if the value in the field isn't what it should be, we can, for example, highlight the field with a red background color or display a message to the user telling the input is wrong.

Of course this will only work if the user has JavaScript enabled. Most browsers these days have JS support and users usually leave it on, but do not forget to validate the form inputs server-side using your scripting language of choice.


Using the events

The two important events are onChange and onKeyUp.

The onChange event fires when the value in an input field changes and the user selects something else, ie. clicks on somewhere else on the page or presses tab.

The onKeyUp event fires every time the user releases a key, ie. when typing.


Here's an example of using onChange


<input type="text" onChange="if(isNaN(this.value)) { alert('The value is not a number'); }" />

The code checks if the value in the field is Not a Number (NaN). If the input is something else than a number, the user gets a message saying "The value is not a number".

Note: the this keyword used in the check refers to the input element itself, so we can use it to get the value of the field


Validating

To make validating the fields easier, let's first create some functions.

Often there are fields that require numeric input, so let's create a function which can be used to check if the value is a number and optionally if it's between some values.

Another task is to limit the maximum input in a field so the user can only write, say, up to 250 characters to a field, so we'll create a function for that too.

Finally we'll also use a regular expression to see if the value in a field is a valid email address.

You can download a script file with all the functions from here, but I suggest you still go through the explanations if you're not completely familiar with them.


Let's start with the number check...

function IsNumber(field,start,end)
{
//Check if value is not a number
if(isNaN(field.value))
return false;

//if start and end are defined
//check if the number is between them
if(start && end)
{
if(field.value >= start && field.value <= end)
return true;
}
else
return true;
}

This function should be pretty simple to understand. The field should be the input element and start and end are the numbers between which the value has to be, but they are optional.

First, we just check if the value in the field is a number at all. If it isn't, we return false. After this we check if start and end are defined and if they are, compare the value to them.



Next, the max size function..

function MaxSize(field,num)
{
//if length of data is > than max,
//make it shorter
if(field.value.length > num)
field.value = field.value.substr(0,num);
}

Yet again, the field should be the input element and num the maximum amount of characters allowed. The length of the value in the field is just compared against the num, and the substr method is used to make its length to num characters if it's too long.


And finally the email check..

function IsEmail(field)
{
//this is a regular expression
var expr = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

//Check if regexp matches the value in the field
if(expr.test(field.value))
return true;

return false;
}

You don't need to understand the syntax of the regular expression, just know that it matches only valid email addresses, so we can use it to test whether or not the value is a valid email address.


With these functions you can easily validate values in forms, but let's define one more function. This one can be used to highlight a field in some color

function Highlight(obj,col)
{
//just set the bgcolor of obj to col
obj.style.backgroundColor = col;
}

Yeah, we could probably just write obj.style.backgroundColor = 'something' when we want to change the color, but that's so much simpler to use and that's why we define it as a function.


Using our validation functions

Look at this example page which uses these functions. I'll explain the details of the code on that page here.

First there is the number only field

<input type="text" name="num" onchange="if(!IsNumber(this,1,100)) { this.value = 1; Highlight(this,'red'); } else { Highlight(this,''); }" />

the code in the onchange event first uses the IsNumber function to see if the value in the field is between 1 and 100. As there's the ! in front, the if is true when the value is NOT a number.

If the value isn't a number between 1 and 100, it sets the fields value to 1 with this.value = 1. Then it uses the Highlight function to highlight the field in red.

The else segment runs when the value is a number between 1 and 100. The only thing we do there is set the background color of the field to '' which in this case is the default "no color" value. We need it because the fields background might be red if the user had inputted an incorrect value first, so when he inputs a correct one the background will stop being red.


Next there's a textarea which allows only 20 characters. As you can see from this, these functions also work on textareas.

<textarea rows="5" onkeyup="MaxSize(this,20)">Max 20 chars!</textarea>

This one is very simple. When the user has typed in a key, it just uses MaxSize to crop the length if it's over 20 characters.


Lastly, the email field.

<input type="text" value="only.valid@email.com" onchange="if(!IsEmail(this)) { Highlight(this,'red'); } else { Highlight(this,''); }"/>

This one is pretty similar to the number only one. The field gets a red background if the value is not a valid email address.



There's one thing, however, which isn't demosntrated on that page but is quite important. It's the empty field check. You should do this when the user presses the submit button on the form.

Here's how it works:

First, set the onsubmit event of the form..
<form ... id="myform" onsubmit="return FormCheck()">

then create a function called FormCheck


function FormCheck()
{
//First, get the form element
var f = document.getElementById('myform');

//Now we can easily check values in fields like this
if(f.fieldName.value == '')
{
Highlight(f.fieldName,'red');

//if we return false, the form won't be submitted
//so the user can fix his errors
return false;
}

//if all was ok, return true so the form gets submitted
return true;
}

Checking if a field is empty is simple as you can see from that. Notice how I defined the form an ID so I can use the getElementById function there. Accessing inputs in a form is very simple after you have the form element, just put the fields name there as shown in the code.




As you can see, checking forms like that is very simple with JavaScript, yet it's not used almost at all. I wonder why...

Labels: ,

1 Comments:

  • Hot stuff! You can bet that I'm going to use that on my sites.

    By Anonymous Anonymous, at 6:56 PM  

Post a Comment

<< Home