Friday, February 23, 2007

Textbox Date Validator - Javascript

I needed to validate 3 textboxes for making a date input on a web page., but I needed to verify the content that the user was entering in the webpages. So I came up with the following Javascript Function:

function text_check(id,x)
{

var text,i,value,status;
var nr = new Array()
nr[0]="0";
nr[1]="1";
nr[2]="2";
nr[3]="3";
nr[4]="4";
nr[5]="5";
nr[6]="6";
nr[7]="7";
nr[8]="8";
nr[9]="9";

text = document.getElementById(id).value;

text = text.substr(text.length-1);
i=0;

while(i<=10)
{
if(text!=nr[i])
{
value=false;
}
else
{
value=true;
break;
}
i++;
}

if(value!=true)
{
if(x=="true"){alert("You cannot imput "+text+" character! Only Numbers!");}
text = document.getElementById(id).value;
text = text.substr(0,text.length-1);
document.getElementById(id).value = text;
}

}

You just call it and enter the ID of the textbox. here is an example:

< id="birth_date_1" name="birth_date_1" onkeydown="text_check('birth_date_1','false')" onkeyup="text_check('birth_date_1','true')" onclick="text_check('birth_date_1','false')" style="width: 30px;" maxlength="2" type="text" width="30">

It does not look very pretty but it get's the job done. The long content can be placed in a dinamic PHP function that will make it more pretty.

1 comment:

Anonymous said...

Nice information, I really appreciate the way you presented.Thanks for sharing..

http://www.w3cvalispdation.net/