0

Checking fields:

checkFields = function() {
  var colCheck = 0;
  var colArray = [];
  var colDupArray = [];
  var iDate = $("check_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;
    }

Validation:

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 === dteDate.getDate() && 
+month === dteDate.getMonth() &&
+year === dteDate.getFullYear();
}

The problem is that my code is accepting a date such as "03.06.2012" when I only want it to accept slashes between the numbers.

It also accepts "03/06/12" when I only want a four digit year.

Any ideas?

Alias
  • 415
  • 6
  • 19
  • Why not use your formatter to render a valid date to your textfield? You are trying to validate a text field against your format. http://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date/16314504#16314504 – Tim Vermaelen May 01 '13 at 14:47
  • see http://stackoverflow.com/questions/51224/regular-expression-to-match-valid-dates for inspiration too – Aprillion May 01 '13 at 15:04
  • Your `isValid` function is completely messed up. Is that only a c&p error or the actual code you're using? It will never return `true`. – Bergi May 01 '13 at 15:07
  • Can you add HTML As well? – Amit May 01 '13 at 15:21

3 Answers3

2

As suggested this let's the user enter a date in a format of choice. The output should be as expected for you.

I've expanded my little demo with a Date.prototype.formatDateField and a library called moment which also seems to be pretty clean. As third option the jQuery-UI $.datepicker.formatDate()

Still this isn't bulletproof and maybe you should look for a datepicker which can handle the format for you. The best solution to your problem imho.

If you want to go custom however this might get you started:

// prototype
Date.prototype.formatDateField = function (options) {
    var i = 0,
        date = [],
        len = date.push(this.getDate(), this.getMonth() + 1, this.getFullYear());

    for (; i < len; i += 1) {
        var chunk = date[i];
        date[i] = chunk < 10 ? options.pad + chunk : chunk;
    }

    return date.join(options.separator);
};

// Setup output
var cfg = {
    fieldDate: "#fieldDate",
    options: {
        pad: "0",
        format: "dd/MM/yyyy",
        separator: "/"
    }
};

// function to call
function reformatInput(){
    $(cfg.date).blur(function(){
        var moment = moment(this.value).calendar(cfg.options2.format),
            prot = new Date(this.value).formatDateField(cfg.options2),
            jqueryui = $.datepicker.formatDate(cfg.options2.format, new Date(this.value));

        $(cfg.fieldDate1).val(moment);
        $(cfg.fieldDate2).val(prot);
        $(cfg.fieldDate3).val(jqueryui);
    });
}

// run on demand
reformatInput();

demo: http://jsfiddle.net/tive/YvdKA/

Tim Vermaelen
  • 6,001
  • 1
  • 22
  • 36
  • +1 on moment.js. it can be glorious once you get the hang of it. (its website is also pretty remarkable.) – arturomp May 02 '13 at 16:07
1

At least for the four-digit-year problem, look at this jfiddle output and the code:

d1 = new Date(1,2,3);
d2 = d1.getFullYear();
d3 = d1.getMonth();
d4 = d1.getDay();
alert(d2);
alert(d3);
alert(d4);

The Date constructor is not strict about four year digits (despite what Mozilla says you should do). In the example above, it's even taking the int 1 as a year! That is reflecting in your program accepting years that aren't 4 characters in length.

Perhaps test the length of the year string?

As for the split, perhaps you can use a regular expression that would both split and make sure that you're only accepting slashes (as suggested here)?

Community
  • 1
  • 1
arturomp
  • 26,187
  • 10
  • 39
  • 64
  • thanks @Bergi! my bad with the original ordering of the parameters. – arturomp May 01 '13 at 15:09
  • But you're still entering a 13th month? That's the reason why it alerts `14`, btw. – Bergi May 01 '13 at 15:10
  • Thanks @Bergi! I've simplified it and clarified in the response, since the point is that the constructor isn't strict about the year it takes. – arturomp May 01 '13 at 15:19
1

You somehow mixed a formatting with a validating function. This is how it should be:

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

    return +day === dteDate.getDate()
        && +month === dteDate.getMonth()
        && +year === dteDate.getFullYear();
}
function formatDate(dteDate) {
    var day = dteDate.getDate(),
        month = dteDate.getMonth() + 1,
        year = dteDate.getFullYear();

    var formatted = (day < 10 ? "0" : "") + day + "/"
                  + (month < 10 ? "0" : "") + month + "/"
                  + year;
    return formatted;
}
Bergi
  • 513,640
  • 108
  • 821
  • 1,164