Forum Moderators: open

Message Too Old, No Replies

javascript date validation script

         

snehula

12:28 pm on Jun 13, 2011 (gmt 0)

10+ Year Member



Hi there :-) I'm trying to write an input validation script for a date field, not being concerned whether the number entered is a valid month day or a valid year, not at the moment at least, only want to check if the character is a number and add slashes in between. So, the affected textbox looks like:

<input type=\"text\" name=\"shutoff\" value=".$shutoff." onkeyup =\"validField(this.value)\">


This actually comes from a php script as part of a longer content string to be inserted into a div tag on page load, that's why i have all those slashes to escape the quotes. Now the javascript function validField is in my head section of the page and looks like this (warning: this might be an xtremely stupid try to make stuff work so before u get a heart attack, take a deep breath):

function validField(txtfield) {
if (txtfield.length <= 10)
{
var checklist = '0987654321';
//compare last entered char to checkList string
var x = checkList.indexOf(txtfield.charAt(txtfield.length-1));
if(x == -1) { //if character is not numeric, delete last character
txtfield = txtfield.substring(0, txtfield.length -2);
this.value = txtfield;
//i dunno how to do the above in the right way, this is trying to
//set the textbox value to itself minus invalid character
//i'm assuming 'this' refers to the textbox object that called the
//function
}
else { //add slash after day
if (txtfield.length == 2) {
txtfield = txtfield + "/";
this.value = txtfield;}
else if (txtfield.length == 5) { //add slash after month
txtfield = txtfield + "/";
this.value = txtfield;}
}
}
else {alert("Please keep the date format, which is: dd/mm/yyyy!");}
}


Obviously, I'm not a javascript guru and this poor little script doesnt work.. Looking forward to your wise words :-)

rocknbil

5:51 pm on Jun 13, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Textual input of a date format is kinda crazy, extremely error prone and can create all sorts of problems server side (not to mention international conflicts.) Any time you trust the user to Do The Right Thing, they will find a way not to. Why don't you use select lists for MM DD YYYY instead? Set the first value as empty:

<select name="month" id="month">
<option value="">-</option>

Then all you have to do is check that the selected index of each list > 0.

snehula

8:51 pm on Jun 13, 2011 (gmt 0)

10+ Year Member



thanks m8.. anyway, this is for a smallish group of users and it was their wish to be able to input date like this (only god knows why)..