问题
My Datepicker code
$(function(){
$( "#task_start_date").datepicker({
dateFormat: 'dd-M-yy',
showOn: 'button',
buttonImage :image_us,
buttonImageOnly: true
});
});
HTML Input:
<input type="text" class="form-control validate[required,custom[date]]" name="task_start_date" id="task_start_date" />
JS function for Correct Date input validation:
"date": {
// Check if date is valid by leap year
"func": function (field) {
var pattern = new RegExp(/^(\d{4})[\/\-\.](0?[1-9]|1[012])[\/\-\.](0?[1-9]|[12][0-9]|3[01])$/);
var match = pattern.exec(field.val());
if (match == null)
return false;
var year = match[1];
var month = match[2]*1;
var day = match[3]*1;
var date = new Date(year, month - 1, day); // because months starts from 0.
return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
},
"alertText": "* Invalid date, must be in YYYY-MM-DD format"
},
Here the regex expects YYYY-MM-DD (2014-11-26) format but we are using dd-M-yy(01-MAR-12) format.
Regex Tried:
/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/
The above regex did not work. How can I change the regex to match the expected datepicker output. The value inserted in DB is 01-MAR-12 and not 2014-11-26.
Thanks.
回答1:
^(0?[1-9]|[12][0-9]|3[01])[-][A-Z]{3}[-]\d{2}$
This should do the trick. The regex you tried was for the format of dd/mm/yyyy or dd-mm-yyyy.
回答2:
Try this (not tested):
(?:0[1-9]|1[0-9]|2[0-9]|3[01])-(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)-\d{2}
(?:0[1-9]|1[0-9]|2[0-9]|3[01]): match 01 to 09, 10 to 19, 20 to 29, 30 to 31. But Feb doesnt have anything over 29 so how you deal with that we not be regex based-: match hypen(?:JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC): matches month-: match hypen-\d{2}: match any two digits in any order
You can shrink the regex but I dont have time right now.
回答3:
Use this one
"date": {
// Check if date is valid by leap year
"func": function (field) {
var pattern = new RegExp(/^(0?[1-9]|[12][0-9]|3[01])[\/\-\.](0?[1-9]|1[012])[\/\-\.](\d{4})$/);
var match = pattern.exec(field.val());
if (match == null)
return false;
var year = match[3];
var month = match[2]*1;
var day = match[1]*1;
var date = new Date(year, month - 1, day); // because months starts from 0.
return (date.getFullYear() == year && date.getMonth() == (month - 1) && date.getDate() == day);
},
"alertText": "* Invalid date, must be in dd-mm-yyyy format"
},
来源:https://stackoverflow.com/questions/27142916/jquery-validation-engine-change-date-format