views:

39

answers:

3

Im using the jQuery validate plugin and was wondering if there was a way to validate if the date entered into a field was a date like yyyy-mm-dd AND the the date falls between Nov 29 2010 - Dec 15 2010

Im pretty new to jQuery so if there is an answer please dumb up the answer as much as possible so i can get through it. Thanks a lot for any/all suggestions

A: 

I've never used the validation plugin, but a look through the API suggests that something like this might work:

$.validator.addMethod('daterange', function(value, element) {
    if (this.optional(element)) {
        return true;
    }

    var startDate = Date.parse('2010-11-29'),
        endDate = Date.parse('2010-12-15'),
        enteredDate = Date.parse(value);

    if (isNan(enteredDate)) {
        return false;
    }

    return ((startDate <= enteredDate) && (enteredDate <= endDate));
});

You would then, I think, need to add the daterange class the the appropriate element.

lonesomeday
+1  A: 

lonesomeday's answer is pretty close, with a few tweaks. I would end the code as follows:

    if(isNaN(enteredDate)) return false;

    return ((startDate <= enteredDate) && (enteredDate <= endDate));
}, "Please specify a date between 2010-11-29 and 2010-1215");

This fixes the isNaN function, and also provides an error message to your users so they know what you're looking for.

Emily
+1  A: 

If you want a reusable function, you might extend Emily and lonesomeday's answers to allow an argument to be provided:

$.validator.addMethod('daterange', function(value, element, arg) {
     // Same as above

     var startDate = Date.parse(arg[0]),
         endDate = Date.parse(arg[1]),
         enteredDate = Date.parse(value);       
     // Same as below

 }, $.validator.format("Please specify a date between {0} and {1}."))

See the source of the jQuery validation range method for an example.

Connor M