簡體   English   中英

客戶端自定義數據注釋驗證

[英]Client-side custom data annotation validation

我已經創建了一個自定義數據注釋來對我的視圖模型進行一些驗證。 問題是它沒有在客戶端驗證。 這是我的模特:

public class MemberViewModel
{
    [ScaffoldColumn(false)]
    public int MemberId { get; set; }

    [Required(ErrorMessage = "Name is required")]
    public string Name { get; set; }

    //My custom data annotation
    [EnforceTrue(ErrorMessage = "You must agree to the Terms and Conditions")]
    public bool AgreeTerms { get; set; }
}

我的數據注釋驗證碼:

public class EnforceTrueAttribute : ValidationAttribute, IClientValidatable
{
    public EnforceTrueAttribute() { }

    public override bool IsValid(object value)
    {
        return value != null && (bool)value == true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        yield return new ModelClientValidationRule() { ValidationType = "enforcetrue", ErrorMessage = this.ErrorMessageString };
    }
}

我的控制器方法:

[HttpPost]
public ActionResult Index(MemberViewModel viewModel)
{
    Member member = new Member();
    TryUpdateModel(member);

    if (ModelState.IsValid)
    {
        _membersRepository.SaveMember(member);

        return RedirectToAction("Index", "Home");       
    }

    return View(viewModel);     // validation error, so redisplay same view            
}

我的觀點是:

@using (Html.BeginForm("Index", "Members", FormMethod.Post)) {

    @Html.HiddenFor(m => m.MemberId)

    <div class="editor-label">@Html.LabelFor(model => model.Name)</div>
    <div class="editor-field">@Html.TextBoxFor(model => model.Name)</div>

    <div class="editor-field">@Html.CheckBoxFor(model => model.AgreeTerms) <label for="AgreeTerms">I agree to the Terms and Conditions</label></div>

    <p>
        <input type="submit" value="Submit" />
    </p>

    @Html.ValidationSummary()
}

所以我的所有其他錯誤消息都會在客戶端驗證的驗證摘要中顯示出來。 但是對於我的自定義數據注釋,錯誤消息在模型的其余部分有效之前不會顯示,並且在您提交表單和頁面重新加載之后,錯誤顯示在摘要中。

我還需要做些什么來讓它在其他錯誤的摘要中顯示出來嗎?

我正在使用C#和ASP.NET MVC 3

最近有同樣的問題。 你可以寫:

$.validator.addMethod('enforcetrue', function (value, element) {
    return $(element).is(":checked");
});
$.validator.unobtrusive.adapters.add('enforcetrue', [], function (options) {
    options.messages['enforcetrue'] = options.message;
    options.rules['enforcetrue'] = options.params;
});

類似的問題這里ASP.NET MVC 3客戶端驗證

實現Iclientvalidatable只會為生成的html輸入添加不顯眼的屬性。 要在客戶端啟用驗證,您必須編寫使用這些不顯眼的屬性驗證輸入的驗證器。 在這里,您可以在asp.net mvc 3中找到客戶端和服務器驗證的非常好的解釋

暫無
暫無

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

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