开发者

Validate date between multiple dates in jQuery.validate and datepicker

I'm using jQuery.datepicker and jQuery.validate. In my form I have multiple date ranges:

2010-02-10 - 2010-02-18
2010-03-01 - 2010-03-12
2010-03-15 - 2010-03-19

etc.

Now I need to validate the datepicker field to check if the date set in the datepicker is between any of those date ranges. For instance, 2010-01-01 would be invalid, as would 2010-02-19.

I've seen many answers but they don't really relate to multiple ranges, as far a开发者_JAVA技巧s I can see.

Does anyone know a solution or at least a pointer to get me in the right direction. I'm thinking of maybe looping each date range in a .each() and running a validation in there. But there is probably a better way.


Your question is something I've been trying to figure out for a while too. This is what I have so far.

I use this for validating a single date range. It takes input fields as params rather than dates:

jQuery.validator.addMethod("rangeDate", function(value, element, params) {
    try {
        var beforedate=$.datepicker.parseDate($(params[0]).datepicker('option','dateFormat'),$(params[0]).val());
        var afterdate=$.datepicker.parseDate($(params[1]).datepicker('option','dateFormat'),$(params[1]).val());
        var qdate=$.datepicker.parseDate($(element).datepicker('option','dateFormat'),value);
        return this.optional(element) || (qdate >= beforedate && qdate<=afterdate);
    } catch(err){
        return false;
    }
}, function(params){
    return "Date must occur between " + $(params[0]).val() + ' and ' + $(params[1]).val();
}
);

and the rule looks like this:

rules:{
  between_date: { dateCan: true, 
         rangeDate:  {
            depends: function(element) { //check that params exist
                return $("input[name='before_date']").valid()
                       && $("input[name='after_date']").valid();
            },
            param:  ["input[name='before_date']", "input[name='after_date']"]
         }
  }
}

After experimenting a bit, I've seen that it's possible to have more than one rangeDate rule for a field. However, the last call appears to overwrite the results of all the previous rangeDate calls for that field. So I think what might work is to add another custom rule that accepts an array of pairs of fields which can be fed to rangeDate. The problem with this approach is that the the depends clause for the rangeDate rule becomes unwieldy as you get more date pairs. This is especially so if you only require at least one pair to be present rather than all pairs.

Of course, if the date ranges aren't dynamic, the problem is easier because no depends clause is necessary. Just rewrite rangeDate to accept dates rather than fields and write a wrapper rule to accept an array of pairs of dates.

If you've found a solution to the problem, I'd love to see it. Hopefully it will be more elegant than mine.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜