javascript 如何使用kendo验证器验证日期格式为yyyy-MM-dd?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14127305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to validate a date is in the format yyyy-MM-dd using kendo validator?
提问by James
I have a kendo date picker that is constructed as follows:
我有一个构建如下的剑道日期选择器:
$("#date").kendoDatePicker({
format: "yyyy-MM-dd",
footer: " ",
parseFormats: ["MM/dd/yyyy", "dd/MM/yyyy"]
});
I would like to use the kendo validator to validate that the date contains a valid date in the format of yyyy-MM-dd. I have tried this:
我想使用kendo验证器来验证日期是否包含yyyy-MM-dd格式的有效日期。我试过这个:
<input type="date" id="date" placeholder="yyyy-mm-dd" name="date" required data-required-msg="Please enter a date." data-date-msg="Please enter a valid date."/>
While the validator does correctly validate the "required" condition, it does not seem to validate that the date is in the correct format or is a valid date. For instance, "abc" passes as a valid date as does 2013-18-85. How can I use the validator to ensure a valid date in the correct format?
虽然验证器确实正确验证了“必需”条件,但它似乎并未验证日期格式是否正确或是否为有效日期。例如,“abc”作为有效日期传递给 2013-18-85。如何使用验证器确保日期格式正确?
回答by OnaBai
If you want to validate
a date
you need to define a rule (no built-in rule).
如果你想要validate
一个date
你需要定义一个规则(没有内置规则)。
Try defining:
尝试定义:
$("#date").kendoValidator({
rules: {
date: function (input) {
var d = kendo.parseDate(input.val(), "yyyy-MM-dd");
return d instanceof Date;
}
}
});
NOTE:Remember that KendoUI first uses parseFormats
option for parsing the date, then converts it to the format
option and finally run validations. That's why I use in validation yyyy-MM-dd
and not ["MM/dd/yyyy", "dd/MM/yyyy"]
.
注意:请记住,KendoUI 首先使用parseFormats
选项来解析日期,然后将其转换为format
选项,最后运行验证。这就是为什么我在验证中使用yyyy-MM-dd
而不是["MM/dd/yyyy", "dd/MM/yyyy"]
.
回答by ADM-IT
The answer is:
答案是:
<script src="@Url.Content("~/Scripts/kendo/2015.2.805/kendo.aspnetmvc.min.js")"></script>
<script type="text/javascript">
kendo.ui.validator.rules.mvcdate = function (input) {
//use the custom date format here
//kendo.parseDate - http://docs.telerik.com/kendo-ui/api/javascript/kendo#methods-parseDate
return !input.is("[data-val-date]") || input.val() === "" || kendo.parseDate(input.val(), "@(MvcApplication.AppCulture.DateTimeFormat.ShortDatePattern)") !== null;
};
</script>
Here is more information: http://docs.telerik.com/kendo-ui/aspnet-mvc/validation
以下是更多信息:http: //docs.telerik.com/kendo-ui/aspnet-mvc/validation
Cheers
干杯