我使用jQuery validate plugin和maskedInput插件为输入做了自定义日期和时间验证。
有没有办法在自定义验证中进行验证,以防止输入比当年更大的一年?
我的代码:
$("#date").mask("99/99/9999 99:99", {
placeholder: "mm/dd/yyyy hh:mm"
});
$.validator.addMethod("dateTime", function(value, element) {
var stamp = value.split(" ");
var validDate = !/Invalid|NaN/.test(new Date(stamp[0]).toString());
var validTime = /^(([0-1]?[0-9])|([2][0-3])):([0-5]?[0-9])(:([0-5]?[0-9]))?$/i.test(stamp[1]);
return this.optional(element) || (validDate && validTime);
}, "Invalid datetime.");
$('#form').validate({
rules: {
date: {
required: true,
dateTime: true
}
},
messages: {
date: {
required: ""
}
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.maskedinput/1.4.1/jquery.maskedinput.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<form action='' method='post' id='form'>
<input type='text' name='date' value='' id='date' placeholder='mm/dd/yyyy hh:mm'>
</form>
答案 0 :(得分:1)
您可以使用addMethod
创建自己的方法,如下所示:
jQuery.validator.addMethod("minDate", function (value, element) {
var now = new Date().getFullYear();
var myDate = new Date(value).getFullYear();
return this.optional(element) || myDate < now;
});
$('#form').validate({
rules: {
date: {
required: true,
dateTime: true,
minDate: true
}
},
messages: {
date: {
minDate: "The date(year) must not be in the future"
}
}
})
希望这有帮助!
答案 1 :(得分:1)
添加检查年份的新方法
cellForRowAtIndexPath
在验证规则中添加相同内容
jQuery.validator.addMethod("minYear", function (value, element) {
var year = new Date(value).getFullYear();
var curentYear = new Date().getFullYear();
return this.optional(element) || year <= curentYear;
}, 'Year can not be greater than current year');