Validating Form Input

by Amrit Hallan
Wednesday, 3rd August 2005

You have learnt that HTML forms are used to gather information from online visitors to your Web site. There are registration forms, there are subscription forms, there are survey forms, and there are navigational forms - forms galore, everywhere.

There are two types of form field processing - server-side and client-side. Processing means, doing something with the information supplied by the form-filler. Server side processing is slower, and involves geeky programming talents in PHP, Perl, C++, JAVA, ASP, CORBA, etc., etc. They are generally some cryptically elite programs residing on the server, the input of the user is sent to them for their worthy solicitude, and they react accordingly. Since every time the programs need to be summoned from the chaotic chambers of an already tormented server, things get really slow. Big fuss, and I personally don't recommend using server-side processing for form fields unless there is an inexorable necessity.

Client-side processing is carried out using either JavaScript or VBScript, as they can be written in the HTML page itself and so, no external program file is needed.

Without further ado, suppose we have this form. Please brace yourself up, as this is going to be a long affair. I suggest first you simply copy and paste the code and view the result, so that accordingly, you can make sense of what's going on. For the moment, this function, bmical() calculates the Body Mass Index (Health experts use it to see how healthy you are) using the following algorithm: 

  1. Accept height in Feet and Inches
  2. Accept Weight in Pounds
  3. Convert height to inches (ft. x 12 + In.) and square it
  4. Multiply weight with 703
  5. Divide 4 by 3 

<script language="JavaScript">

function addthem(val1, val2)
{
val1=val1*1;
val2=val2*1

return val1 + val2;

}

function bmical()
{
var AllInches=0;
var StorePounds=0;
var SquareInches=0;

SquareInches=SquareInches*1;
StorePounds=StorePounds*1;
AllInches=AllInches*1;
AllInches=addthem(calc.hfoot.value*12, calc.hinch.value);
SquareInches=AllInches*AllInches;
StorePounds=calc.weight.value*703;
calc.bmi.value=Math.round(StorePounds/SquareInches);

}

</script>

<body>
<div align="center">
<p><b>BODY MASS INDEX CALCULATOR</b>
</div>

<form name="calc">
<table width="75%" border="1" align="center" bgcolor="#c0c0c0" bordercolor="#800000">
<tr>
<td width="100%" valign="top">

<table width="90%" border="1" align="center" bgcolor="#ffffff">
<tr>
<td width="20%" align="left" valign="top">

<p><font color="#000000" size="2" face="arial"> <b>Height</b> </font>

</td>

<td width="80%" align="left" valign="top">

<input type="text" name="hfoot" size="10">
<font face="arial" size="2">Ft.</font> <input type="text" name="hinch" size="10">
<font face="arial" size="2">In.</font>

</td>

</tr>

<tr>
<td width="20%" align="left" valign="top">

<p><font color="#000000" size="2" face="arial"> <b>Weight</b> </font>

</td>

<td width="80%" align="left" valign="top">

<input type="text" name="weight" size="10"> <font face="arial" size="2">Pounds</font>

</td>

</tr>
</table>

<div align="center">
<input type="button" name="calbmi" value="Calculate BMI" onclick="bmical()">
<input type="reset" name="reset" value="Reset">
</div>

<table width="70%" align="center" border="1" bgcolor="#000000">

<tr>
<td width="30%" align="left" valign="top">

<p><font color="#ffffff" size="2" face="arial"> <b>Your BMI is</b> </font>

</td>

<td width="50%" align="center" valign="top">

<input type="text" name="bmi" size="10">

</td>

</tr>
</table>

</td>

</tr>
</table>

</form>
</body>

I again stress that don't get overwhelmed - this is all you've been learning - it's just that, it's lots of it. In the JavaScript, I have purposely used so many variables so that you can pin point every single calculation. Tables have been used just to render a neat formatting to our form. For an example, you can see the form that is present on almost every page of this web site.

First we deal with the form. The form has five components - text boxes that let the user enter feet, inches and pounds. Then two buttons. The left hand side button calculates the BMI upon clicking, and the right hand side button restores the fields to their pristine form, that is, blank, so that you can re-start your pursuit again.

The function bmical() has been assigned to the "Submit" button's OnClick attribute, that is, whenever somebody clicks this button, the function gets executed (oh, I don't mean it's brutally killed or something).

The JavaScript is easily understandable, as it is simply carrying out mathematical calculations. We have used the pre-learnt Math.round() method here.

Observe how individual form fields have been accessed. For instance, to convert feet to inches:

AllInches=AllInches*1;
AllInches=addthem(calc.hfoot.value*12, calc.hinch.value);
SquareInches=AllInches*AllInches;
StorePounds=calc.weight.value*703;
calc.bmi.value=Math.round(StorePounds/SquareInches);

AllInches is a variable that stores the height in inches. We access the Feet field by using calc.hfoot.value, we access the inches field by using calc.hinch.value. Remember when I had introduced the tag, I had told that the name attribute is needed when we have to access the fields of the form? So what we do to get the Foot information of the form is, get the value of the field hfoot that belongs to the form named calc.

Makes sense? We'll explore it more in the next part. Until then.

This time we'll make a form that collects information about the visitor at your site. You must have filled-in copious registration forms or survey forms where you had to enter your name, your email, your address, etc. Sometimes users, intentionally or unintentionally, enter wrong information that can either spoil your database scheme or give you lots of useless data and hence, waste your precious server space.

To avoid such problems, as much as it can be managed, we programmatically try to make sure, that data is entered in an orderly fashion, and no unusable fields are entered. Checking individual fields of the form does this.

We'll see a form here with three fields: Name, Phone and Email. In this form, no field should be left blank, there should be no numbers in the Name field [1,2,3,4,…], and in the Email field, no email should be without the "@" sign. We can carry out more complex validations, but at the moment, these three should suffice.

<script language="JavaScript1.2">

function CheckName(HoldName)
{
NoNumThere=true;

for(i=0; i<HoldName.length; i++)
{

for(j=0; j<10; j++)
{

if(HoldName.charAt(i)==j.toString())
{

NoNumThere=false;
break;

}

}

if(NoNumThere==false)
{

break;

}

}

return NoNumThere;

}

function CheckMail(HoldMail)
{

IsValid=true;

if(HoldMail.indexOf("@")<=0)
{

IsValid=false;

}

return IsValid;

}

function checkfields()
{

var AllFilled=true;

for(i=0; i<3; i++)
{

if(visitor.elements[i].value.length==0)
{

alert("The field [" + visitor.elements[i].name + "] can not be left blank.");
AllFilled=false;
visitor.elements[i].focus;
return;

}

}

if(AllFilled==true)
{

var NameValid=true;
var EmailValid=true;
NameValid=CheckName(visitor.vname.value);
EmailValid=CheckMail(visitor.vemail.value);

if(NameValid==false)
{

alert("Sorry, your name can not contain numbers.");
visitor.vname.focus;

}

if(EmailValid==false)
{

alert("Sorry, this does not seem like a valid email address.");

}

}

if(NameValid==true & EmailValid==true)
{

alert("RIGHTO!!!");

}

}

</script>

<body>
<form name="visitor">
Enter your name: <input name="vname" type="Text">
<br>
Enter you phone: <input name="vphone" type="Text">
<br>
Enter your email: <input name="vemail" type="Text">
<br>
<input type="Button" name="submit" value="Submit" onclick="checkfields();">
<input type="Reset" name="reset" value="Reset">
</form>
</body>
</html>

Copy and paste the code as it is, and save the entire content as a new HTML page. Then load it on to your browser. Unless you see the result, it'll be difficult to follow the script if you do not have prior programming background. The first condition is, none of the fields can be submitted blank. Click on the submit button without entering anything and observe the reaction.

Here, we are making ample use of the recently learnt for(){…} loop. Then we have used function too, to carry out certain validations. Our main function, checkfields(), is associated with the OnClick attribute of the "Submit" button, that is, when you click on the "Submit" button, this function gets triggered.

Some new terms in today's script are: true, false, charAt(), toString(), break, indexOf(), string.length, and form.elements[ ].

A quick explanation to make things easier:

If at 10:30 pm, I say, "It is night", then

var fact=true;

and if I say at 10:30 pm that "It's afternoon", then

var fact=false;

Which explains the use of true and false, which are also called Boolean operators, which means, a Boolean variable can either be true or false, but NEVER both.

Until we learn about arrays, every character in a string has an index position. For instance, if we have

var city="Delhi";

then city.charAt(0)="D", city.charAt(1)="e", city.charAt(2)="l"…..city.charAt(4)="i".

toString(), converts another data type to a string data-type. For example,

var num1=31;
var num2=21;
var char1=num1.toString();
var char2=num2.toString();

So,

num1+num2=52;

and

char1+char2=3221;

In the second case, instead of being added, the variables are being concatenated, which indicates that they are strings, not numbers. We'll see its application later.

break, true to its name, breaks something. In this case, it breaks the loop in which it occurs, and takes the execution of the program to the line immediately after the loop, without meeting the condition required to complete the loop.

indexOf() tells us about the position of a particular character in a string. Look its use in the following code:

var city="Delhi";

Referring to this code, city.indexOf("e") should give us a value 1 and city.indexOf("h") should give us a value 3. city.indexOf("z") should give us a value less than zero, indicating that it does not belong to the given string.

String.length gives us the length of the string, for instance, if city="Delhi", then city.length would give us 5.

Again, elements[ ] is an array, and we haven't dealt with them yet, so we leave the rest of the explanation to the next section.


Amrit Hallan is a freelance web designer. For all web site development and web promotion needs, you can get in touch with him at amrit@bytesworth.com . For further details, visit http://www.bytesworth.com You can subscribe to his newsletter [BYTESWORTH REACHOUT] on Web Designing Tips & Tricks by sending a blank email at bytesworth-subscribe@topica.com.
View the original article Validating Form Input