簡體   English   中英

FluentValidation謂詞驗證器不起作用

[英]FluentValidation predicate validator doesn't work

我有模型課:

[FluentValidation.Attributes.Validator(typeof(CrcValidator))]
public class CrcModel
{
    [Display(Name = "Binary value")]
    public string binaryValue { get; set; }

    [Display(Name = "Generator")]
    public string generator { get; set; }
}

和帶有謂詞的驗證器類:

public class CrcValidator : AbstractValidator<CrcModel>
{
    public CrcValidator()
    {
        RuleFor(x => x.binaryValue)
            .NotEmpty().WithMessage("Binary value is required")
            .Matches(@"(0|1)*").WithMessage("This value is not valid binary value");

        RuleFor(x => x.generator)
            .NotEmpty().WithMessage("Generator is required")
            .Matches(@"(0|1)*").WithMessage("Generator must be valid binary value")
            .Must(CompareLength).WithMessage("Length must be lesser than length of binary value - 1");
    }

    private bool CompareLength(CrcModel model, string value)
    {
        return model.binaryValue.Length - 1 > model.generator.Length;
    }
}

我將斷點放置在CompareLength函數中,並且從表單正確讀取了每個值。 問題是即使我的謂詞函數返回false,我的表單也通過了驗證。 NotEmpty和Matches規則只能完美地工作必須似乎已被忽略。

編輯

jQuery的提交按鈕(類型為“按鈕”):

$(function () {
$("#Button1").click(function () {
    var form = $("#Form1");
    if ($(form).valid()) {
        $.ajax({
            type: 'POST',
            url: 'Compute',
            data: $(form).serialize(),
            success: function (result) {
                $("#remainder").val(result.remainder);
                $("#signal").val(result.signal);
            }
        });
    }
}); 
});

控制器動作處理表提交:

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Compute([Bind(Include = "binaryValue,generator")] CrcModel model)
    {
        if (ModelState.IsValid)
        {
            model.remainder = ComputeFrame(model.binaryValue, model.generator);
            model.signal = model.binaryValue + model.remainder;
        }

        return Json(new { remainder = model.remainder, signal = model.signal });
    }

來自Must規則的驗證可在服務器端使用,但消息不會顯示。

編輯:經過幾句評論,在FluentValidation中對Must所有調用中定義的驗證僅在服務器上執行。 沒有任何JavaScript等效於任意C#代碼。 MVC框架將C#中的FluentValidation規則轉換為HTML表單字段標記上的各種HTML5 data-*屬性,jQuery Validate在客戶端驗證期間讀取這些屬性。 由於無法將謂詞(委托方法)中定義的驗證規則轉換為HTML5 data-*屬性,因此這些驗證規則僅可在服務器端執行。

編輯#2:鑒於Must驗證是由AJAX調用觸發的,因此您需要做一些事情:

  1. 將HTTP狀態代碼設置為非200響應,以觸發jQuery中的錯誤處理機制。 另外,將HTTP狀態設置為422(不可處理實體)

     HttpPost] [ValidateAntiForgeryToken] public ActionResult Compute([Bind(Include = "binaryValue,generator")] CrcModel model) { if (ModelState.IsValid) { model.remainder = ComputeFrame(model.binaryValue, model.generator); model.signal = model.binaryValue + model.remainder; return Json(new { remainder = model.remainder, signal = model.signal }); } else { Response.StatusCode = 422; return Json(new { errors = ModelState.Errors }); } } 
  2. 更改jQuery.ajax調用:

     $(function () { $("#Button1").click(function () { var form = $("#Form1"); if ($(form).valid()) { $.ajax({ type: 'POST', url: 'Compute', data: $(form).serialize(), success: function (result) { $("#remainder").val(result.remainder); $("#signal").val(result.signal); }, error: function(xhr) { if (xhr.status == 422) { var errors = JSON.parse(xhr.responseText); console.log(errors); } } }); } }); }); 

一種替代方法是只渲染將一個或多個錯誤消息顯示為HTML的Partial,然后在DIV中設置該HTML並顯示DIV標簽。

暫無
暫無

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

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