topcat3
topcat3

Reputation: 2642

Simple Javascript Validation

I have a field for date e.g. dd/mm/yyyy . I have validate code that won't allow a user to proceed once the date is not it the correct format dd/mm/yyyy

What I want to do is have a new field that has the default value dd/mm/yyyy in the field. I want the user to be able to leave this field as is dd/mm/yyyy and proceed or else if they enter anything else in the field it needs to be a valid date. So dd/mm/yyyy is accepted and any valid date e.g. 12/12/2012

else if(!validateDate(document.lending.date.value)){alert("Please enter a valid date. The date must be of the format dd/mm/yyyy");document.lending.date.focus();return false;}                                                          




function validateDate(thedate){
 if(thedate.length <11)
    {
try{
  day = thedate.substring(0,2);
  mmonth = thedate.substring(3,5);
  year = thedate.substring(6,10);
  if((thedate.charAt(2)!="/") || (thedate.charAt(5)!="/") || (day<1) || (day>31) ||     (mmonth<1) || (mmonth>12) || (year<1999) || (year>9999) ||     (!validateNumberWithoutDecimal(day)) || (!validateNumberWithoutDecimal(mmonth)) ||     (!validateNumberWithoutDecimal(year)))
     {
       return false;
     }
  else
     return true;
}catch(e){return false;}
 }
 else
 return false;

}

I'm thinking to write a new function validateMyNewDate and do it that way so that it accepts dd/mm/yyyy aswell as validating the date. just a bit confused with my logic now.

Upvotes: 1

Views: 1109

Answers (1)

David Hellsing
David Hellsing

Reputation: 108530

You can try validating using the Date constructor instead:

var isValidDate = function(str) {
    return !!new Date(str).getTime();
}

It should work for the 'dd/mm/yyyy' format, f.ex:

isValidDate('12/12/1999'); // true
isValidDate('12/52/1999'); // false

If you want to make sure the user used the exact 'dd/mm/yyyy' format, you can combine it with a regex:

Update: added so it also validates a default input of "dd/mm/yyyy".

var isValidDate = function(str) {
    return str == 'dd/mm/yyyy' || 
           ( /^\d{2}\/\d{2}\/\d{4}$/.test(str) && new Date(str).getTime() );
}

Upvotes: 4

Related Questions