我有一个文本输入,用户输入出生日期。他们可以使用包含的jQuery日期选择器,也可以使用mmddyy,mm / dd / yy或mm-dd-yy格式输入,具有2位或4位数年份。我手动将它们的格式转换为mm / dd / yyyy。
我目前的代码到目前为止,只要用户没有按Enter键。如果他们这样做,并且该框的格式不是mm / dd / yy或mm / dd / yyyy,则datepicker会将值更改为今天的日期。有没有办法让日期选择器像这样覆盖日期?
这是我的整个事情的JS代码:
var datebox = $('#applicant_dob');
datebox.datepicker({
constrainInput: false,
changeYear: true,
changeMonth: true,
showOn: "focus",
dateFormat: "mm/dd/yy",
yearRange: "-100:+0",
showOptions: { direction: "down" },
onClose: function(e, c) {
var d = $(this);
datepickerOnClose(e, d);
}
});
function datepickerOnClose(e, d){
var changeFlag = true;
if(/^(\d{2})[\/](\d{2})[\/](\d{4})$/.test(e)){
changeFlag = false;
}
//change yy to yyyy if needed
//(assumes date is in mmddyy, mm/dd/yy, or mm-dd-yy format
if(/^(\d{2})[\/-]?(\d{2})[\/-]?(\d{2})$/.test(e)){
var yy = e.substr(e.length - 2, 2);
var yyyy = yy >= 15 ? 19 + yy : 20 + yy;
e = e.substring(0, e.length - 2) + yyyy;
d.val(e);
}
//convert to mm/dd/yyyy
if(/^\d{8}$/.test(e)){
d.val(e.slice(0, 2) + '/' + e.slice(2, 4) + '/' + e.slice(4, 8));
changeFlag = true;
}else{
if(/^(\d{4})[\/-](\d{2})[\/-](\d{2})$/.test(e)){
d.val(e.replace(/^(\d{4})[\/-](\d{2})[\/-](\d{2})$/, "$2/$3/$1"));
changeFlag = true;
}else{
if(/^(\d{2})-(\d{2})-(\d{4})$/.test(e)){
d.val(e.replace(/^(\d{2})-(\d{2})-(\d{4})$/, "$1/$2/$3"));
changeFlag = true;
}
}
}
if(changeFlag){
d.change();
}
}
datebox.on('keypress', function(event){
if(event.which == 13){ //'enter' key
console.log('fired');
datepickerOnClose($(elm).val(), $(elm));
$(elm).focusout();
}
});
编辑: