How to validate a date is in the format yyyy-MM-dd using kendo validator?

六月ゝ 毕业季﹏ 提交于 2019-11-29 22:02:03

问题


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:

<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?


回答1:


If you want to validate a date you need to define a rule (no built-in rule).

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"].




回答2:


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

Cheers



来源:https://stackoverflow.com/questions/14127305/how-to-validate-a-date-is-in-the-format-yyyy-mm-dd-using-kendo-validator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!