Dot separated clientside date validation in asp MVC 4

只谈情不闲聊 提交于 2020-01-28 10:14:05

问题


So I've been banging my head to wall with this problem for hours. I'm creating localized validation for my date input fields. I've overwritten the default jquery date validator and the method seems to be working fine. Everything seems to go as planned but jquery validator just won't let me to post the form.

Breakpoint placed in the custom validation method is hit properly in the firebug and it returns true as it's supposed to.

Once I continue executing, the validation error fields with red rectangles are gone but validation summary still displays the MVC generated property errors.

Here's the code:

tracker.validate.js

// Replace dots so jq validator can understand what's going on
$(function () {
    $.validator.addMethod(
    "date",
    function (value, element) {
        var s = value;
        s = value.replace(/\./g, '/');

        // Chrome requires tolocaledatestring conversion, otherwise just use the slashed format
        var d = new Date();
        return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value))) || !/Invalid|NaN/.test(new Date(s));
    },
    ""
    );
});

$.validator.unobtrusive.parse();

Here are the script references in my partial view, where this form is located

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/tracker.validate.js")" type="text/javascript"></script>

Datetime editortemplate

@model DateTime


<input style="width:44%;display:inline;" type="text" name='@(ViewData.TemplateInfo.HtmlFieldPrefix).Day' value='@Model.Date.ToShortDateString()' class='date'/>
<input style="width:30%;display:inline;" type="text" name='@(ViewData.TemplateInfo.HtmlFieldPrefix).Time' value='@Model.ToShortTimeString()' onblur='formatTimeInput(this)'/>
@Html.HiddenFor(model => model)

Datepicker initialization:

$.datepicker.setDefaults($.datepicker.regional['fi']);

$('.date').datepicker({
    showOn: "button",
    dateFormat: "dd.mm.yy",
    buttonImage: '/content/images/calendarIcon.png',
    buttonImageOnly: true,
    constrainInput: false
});

Is there something I'm missing or is there anyway to get rid of these default property errors?


回答1:


Apparently there was some other script file conflicting with validations. I removed the line

<script src="@System.Web.Optimization.BundleTable.Bundles.ResolveBundleUrl("~/Scripts/js")"></script>

From _Layout.cshtml and it's working now.



来源:https://stackoverflow.com/questions/11756226/dot-separated-clientside-date-validation-in-asp-mvc-4

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