0

Here is my current date validation function:

  isValidDate = function(day,month,year) {
    var dteDate;
    dteDate=new Date(year,month,day);
    return ((day.toString()===dteDate.getDate().toString()) && (month.toString()===dteDate.getMonth().toString()) && (year.toString()===dteDate.getFullYear().toString()));
  }

Then later I check the fields:

checkFields = function() {
  var iDate = $("inspect_date").value;
  if(iDate.length > 0) {
    var a = iDate.split("/"); 
    if(isValidDate(a[0],a[1]-1,a[2]) == false){
      alert("You have entered an invalid date. Please amend!");
      return false;
    }

So at the moment it doesn't accept dates in the format dd/mm/yyy which is what I want - the function doesn't like the leading zero.

I tried to fix it in this way:

isValidDate = function(day,month,year) {
  var dteDate;
  dteDate=new Date(year,month,day);

  var day = dteDate.getDate();
  var month = dteDate.getMonth() + 1;
  var year = dteDate.getFullYear();

  var formatted =
      (day < 10 ? "0" : "") + day + "/"  +
      (month < 10 ? "0" : "") + month + "/"  +
      year;

  return ((day.toString()===dteDate.getDate().toString()) && (month.toString()===dteDate.getMonth().toString()) && (year.toString()===dteDate.getFullYear().toString()));
}

But now my 'return' part is containing the wrong values when it does the comparisons.

Can anyone help?

Alias
  • 415
  • 1
  • 6
  • 20

1 Answers1

3

For the example date "02/04/2012" the first variation of your function passes "02", 3, "2012" as the arguments. Your function then tries to compare "02" with "2" which is obviously "not equal".

You should compare numbers as numbers. Unary + operator is a shortcut to convert a string to a number (+"01" yields 1; you can use parseInt as well):

return
    +day === dteDate.getDate() && 
    +month === dteDate.getMonth() &&
    +year === dteDate.getFullYear();

Here is another way to validate dates using RegRx and JavaScript Date object.

Community
  • 1
  • 1
Salman A
  • 262,204
  • 82
  • 430
  • 521
  • Could you explain what +day, +month, etc. actually are? Also when I try this code, I get my 'Invalid Date' warning still. – Alias Feb 14 '13 at 14:21
  • In my own code, do you know why I'd use `var month = dteDate.getMonth() + 1`? I got the validation code from somewhere else and I don't understand the `+1` part. – Alias Feb 18 '13 at 10:53
  • 1
    getMonth() returns 0-based month numbers (jan=0, dec=11) where as we naturally assume that jan = 1 and dec = 12. The + 1 for convert months to natural month. – Salman A Feb 18 '13 at 11:15