自定义客户端验证(属性)不会在MVC 4中触发

时间:2013-12-04 11:36:12

标签: c# jquery asp.net-mvc validation

我编写了一个验证传入数据的代码。

所有内置验证(RequiredAttribute等)有效 ......

但是我自己的写了DateRangeAttribute 并没有触发帖子上的错误,帖子来到我的控制器:(。

覆盖的IsValid 方法发送回良好(错误)值,并且在服务器端,控制器正确地看到无效的ModelState,但客户端没有。< / p>

数据验证属性在浏览器上呈现为HTML:

我希望在所有数据真正有效之前避开帖子。

有代码:

DateRangeAttribute

public class DateRangeAttribute : RangeAttribute
    {
        public DateRangeAttribute (string minimumYear) 
            :base(typeof(DateTime), minimumYear, DateTime.Now.Year.ToString())
        {
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var inputYear = value as int?;
            var result = (inputYear != null && inputYear >= 1886 && inputYear <= DateTime.Now.Year);

            return result ? ValidationResult.Success : new ValidationResult(GetErrorMessage());
        }

        private string GetErrorMessage()
        {
            return "The year must be greater than 1886 and lower than the actual year.";
        }

        public override string FormatErrorMessage(string name)
        {
            return string.Format(GetErrorMessage(), name);
        }
    }

Create.cshtml

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

<!-- ... -->

@using (Html.BeginForm("Create", "Car", FormMethod.Post, new { id = "CreateForm" }))
{ 
    @Html.ValidationSummary(true)
    <!-- ... -->
        @Html.LabelFor(model => model.Year)
        @Html.EditorFor(model => model.Year)
        @Html.ValidationMessageFor(model => model.Year)
    <!-- ... -->
}

Web.Config file:
<configuration>
    <appSettings>
        <!-- ... -->
        <add key="ClientValidationEnabled" value="true" />
        <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    </appSettings>
    <!-- ... -->
</configuration>

1 个答案:

答案 0 :(得分:1)

您还必须通过IClientValidatable提供自定义客户端验证实施。因此,我建议你直接从ValidationAttribute继承,因为你必须改变几乎所有的东西