FluentValidation谓词验证器不起作用

本文关键字:不起作用 验证 谓词 FluentValidation | 更新日期: 2023-09-27 18:11:10

我有模型类:

[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函数中放置了断点,并且每个值都正确地从form中读取。问题是,我的表单通过验证,即使我的谓词函数返回false。NotEmpty和Matches规则工作得很好,只有Must似乎被提交。

编辑

jQuery for submit button (of type "button"):
$(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 });
    }

必须规则的验证在服务器端工作,但消息没有显示

FluentValidation谓词验证器不起作用

Edit:经过一些注释后,在FluentValidation中对Must的所有调用中定义的验证仅在服务器上执行。JavaScript不存在等同于任意c#代码的东西。c#中的FluentValidation规则被MVC框架转换为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);
                        }
                    }
                });
            }
        }); 
    });
    

另一种方法是只呈现一个Partial,它将一个或多个错误消息显示为HTML,然后在DIV中设置该HTML并显示DIV标记。