Click to See Complete Forum and Search --> : Form Validation of Dates


raynkel
08-22-2003, 09:20 AM
I have written a Java Script that checks for a valid date in the dd/mm/yyyy format. The problem I have is when I call the date back to display it, it strips out the zeros in the date, ie. 01/01/2002 shows as 1/1/2002. So when a user edits a record that exists it sees the date format as incorrect. Is there a way to force it to show it as 01/01/2002 instead of 1/1/2002? I know I could write script to check how many characters are in the date and check it that way, but would be easier if I could just force it to include the zeros.
Any ideas? Thanks

PS: here is the script

if (aForm.txtEND_DATE.value != ""){
var err=0
var a=aForm.txtEND_DATE.value
if (a.length != 10) err=1
b = a.substring(0, 2)// month
c = a.substring(2, 3)// '/'
d = a.substring(3, 5)// day
e = a.substring(5, 6)// '/'
f = a.substring(6, 10)// year
if (b<1 || b>12) err = 1
if (c != '/') err = 1
if (d<1 || d>31) err = 1
if (e != '/') err = 1
if (f<0 || f>9999) err = 1
if (b==4 || b==6 || b==9 || b==11){
if (d==31) err=1
}
if (b==2){
var g=parseInt(f/4)
if (isNaN(g)) {
err=1
}
if (d>29) err=1
if (d==29 && ((f/4)!=parseInt(f/4))) err=1
}

if (err==1) {
alert("Please enter the End Date in 'mm/dd/yyyy' format");
return(false)
}

kernschatten
08-22-2003, 10:10 AM
try these: only caveat is that it doesn't force MM/DD/YYYY. It accepts any combo of a valid date (leading zeros or not). If you need the leading zeros can add a string parse that pushes the zeros in if needed.

function check_Date(input) {
var re = /\d{1,2}/g;
var re1 = /\d{1,2}\/\d{1,2}\//;

var string = re.exec(input.value);
var month = RegExp.lastMatch;
var string = re.exec(input.value);
var day = RegExp.lastMatch;
var string = re1.exec(input.value);
var year = RegExp.rightContext;

if (month == 0)
return error_Handler("The date you entered is invalid. Please enter a MM/DD/YYYY format date.", input);

switch (Number(month)) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if (Number(day) < 1 || Number(day) > 31)
return error_Handler("The date you entered is invalid. Please enter a MM/DD/YYYY format date.", input);
break
case 2:
if ((!(Number(year) % 4 == 0)) || ((year % 100 == 0) && !(year % 400 == 0)))
if (Number(day) < 1 || Number(day) > 28) return error_Handler("The date you entered is invalid. Enter a MM/DD/YYYY format date.", input);
else
if (Number(day) < 1 || Number(day) > 29) return error_Handler("The date you entered is invalid. Enter a MM/DD/YYYY format date.", input);
break
default:
if (Number(day) < 1 || Number(day) > 30)
return error_Handler("The date you entered is invalid. Enter a MM/DD/YYYY format date.", input);
break
}
return true;
}

function error_Handler(msg, input) {
alert(msg);
input.focus();
input.select();

return false;
}