簡體   English   中英

自定義客戶端驗證(屬性)不會在MVC 4中觸發

[英]The custom client-side validation(attribute) doesn't trigger in MVC 4

我編寫了用於驗證傳入數據的代碼。

所有的內置驗證 (RequiredAttribute等)都可以使用 ...

但是我自己寫的DateRangeAttribute 不會在post上觸發錯誤 ,並且post到達我的控制器:(。

重寫的IsValid方法發送回good(false)值,並且在服務器端,控制器可以正確看到Invalid ModelState,而在客戶端則看不到。

數據驗證屬性在瀏覽器上呈現為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>

您還必須通過IClientValidatable提供自定義客戶端驗證實現。 因此,我建議您直接從ValidationAttribute繼承,因為無論如何您都必須更改幾乎所有內容

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM