2

Im trying to validate a datepicker form to check if the first selected date is before the second selected date as shown here: https://www.dropbox.com/s/uwmx64vogm5viyp/Screenshot%202014-04-03%2014.20.38.png

The way I'm currently doing it is:

buildComparisonRule({
name: "dateBefore",
message: "You must select an end date that is after the start date",
validator: function(value, comparedTo){
    var FirstDate = new Date(value);
    var SecondDate = new Date(comparedTo);

    return FirstDate.getTime() < SecondDate.getTime();
}
});

var form = document.getElementById("datepicker_form");

validator(form, [{
    name: "start_date",
    rules: "dateBefore[end_date]"
}]).onError(function(errors){
    console.log(Object.keys(errors))
    for (var error in errors){
        //alert(errors[error])
    }
    $('#start_date').parent().addClass('error');
});

Using the valkyr.js validation libary.

The problem is that atm it only validates on the first part of the DD/MM/YYYY rather than entire string.

Is there any ways to validate on the whole date rather than just the one part of it?

Martin Hobert
  • 203
  • 1
  • 3
  • 10

3 Answers3

2

You are using the Date constructor wrong. There are 4 construtors according mozzila dev site

new Date(); // current date
new Date(value); // int value representing a date since 1 January 1970 00:00:00 UTC 
new Date(dateString); // using Date.parse();
new Date(year, month [, day, hour, minute, second, millisecond]); // see my example


function parseDate(date){
    var d = date.split("/");
    return new Date(d[2], d[1]-1, d[0];
}

var FirstDate = parseDate(value);

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

patricK
  • 1,045
  • 11
  • 27
0

You must format your date before creating date object, try this way:

validator: function(value, comparedTo){
   value = value.split(/\D+/g);
   comparedTo = comparedTo.split(/\D+/g);
   var FirstDate = new Date(value[2],value[1],value[0]);
   var SecondDate = new Date(comparedTo[2],comparedTo[1],comparedTo[0]);

   return FirstDate.getTime() < SecondDate.getTime();

}

radia
  • 1,456
  • 1
  • 13
  • 18
0

I don't think Date() can correctly parse dates in DD/MM/YYYY format. It's not a matter of getting it to read the whole string; the problem is it interprets what it reads in a way you didn't intend.

You could extract the day, month, and year from each date and pass them to the constructor Date(year, month, day). Other solutions are described here:

how to parse a "dd/mm/yyyy" or "dd-mm-yyyy" or "dd-mmm-yyyy" formatted date string using JavaScript or jQuery

Community
  • 1
  • 1
David K
  • 3,147
  • 2
  • 13
  • 19