Reputation: 18550
I need to validate a date using this script in the format of YYYY-MM-DD, but I can't seem to get it working perfectly. With the regular expression I'm using, it allows for users to enter 10 numbers without dashes, instead of 8 with dashes in the correct places. Is there a way to modify my script to fix this?
jQuery.validator.addMethod("date", function(date, element) {
return this.optional(element) || date.match(/^[-0-9]{10}$/);
}, "Please specify a valid date");
Upvotes: 3
Views: 17590
Reputation: 8616
This would validate the exact format with dashes in the correct place.
/^(\d{4})-(\d\d)-(\d\d)$/
Fuller validation to ensure sensible year/month/day values could be
/^(19|20)\d\d-(0\d|1[012])-(0\d|1\d|2\d|3[01])$/
Upvotes: 0
Reputation: 3612
You have a wrong regex.
You can use this one instead :
^\d{4}-((0\d)|(1[012]))-(([012]\d)|3[01])$
So it would be :
return this.optional(element) || date.match(/^\d{4}-((0\d)|(1[012]))-(([012]\d)|3[01])$/);
Upvotes: 10