Fluent Validation 验证器在向其添加验证代码之前会导致错误

Fluent Validation validator results in an error before validation code is even added to it

我正在使用 Contoso 大学项目尝试 Fluent Validation。

所以我在现有 class:

中添加了一个验证器属性
[Validator(typeof(PersonValidator))]
public abstract class Person
{
    public int ID { get; set; }

    [Required]
    [StringLength(50)]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }
}

我的 PersonValidator 还没有做任何事情:

public class PersonValidator : AbstractValidator<Person>
{
    public PersonValidator()
    {
    }
}

但是当我访问学生的创建页面时,我的调试器在 EditorFor 行停止....

 @Html.EditorFor(model => model.LastName, 
      new { htmlAttributes = new { @class = "form-control" } })

……我得到一个错误:

Validation type names in unobtrusive client validation rules must be unique. The following validation type was seen more than once: required

我似乎没有多次对同一元素进行相同的验证,那么为什么我会收到错误消息? Fluent Validation 能否与 MVC 的内置验证一起使用?

如果您将 FluentValidation 与 DataAnnotations 结合使用,就会发生这种情况。尝试在 Application_Start

中做这样的事情
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
FluentValidationModelValidatorProvider.Configure(provider => provider.AddImplicitRequiredValidator = false);
var fluentValidationModelValidatorProvider = new FluentValidationModelValidatorProvider(new AttributedValidatorFactory());
ModelValidatorProviders.Providers.Add(fluentValidationModelValidatorProvider);

根据 this 页面,您可以尝试删除 DataAnnotations 验证。

Compatibility with ASP.NET’s built-in Validation By default, after FluentValidation is executed then any other validator providers will also have a chance to execute as well. This means you can mix FluentValidation with DataAnnotations attributes (or any other ASP.NET ModelValidatorProvider implementation).

If you want to disable this behaviour so that FluentValidation is the only validation library that executes, you can set the RunDefaultMvcValidationAfterFluentValidationExecutes to false in your application startup routine:

services.AddMvc().AddFluentValidation(fv => {
 fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
});

Note If you do set RunDefaultMvcValidationAfterFluentValidationExecutes to false then support for IValidatableObject will also be disabled.

希望对您有所帮助!

我不确定为什么它会向字符串字段添加隐式必需验证器,但是当我将 Fluent Validation Provider 配置为不在我的 Global.asax.cs 文件中添加隐式必需验证器时,问题就消失了:

FluentValidationModelValidatorProvider.Configure(provider 
    => provider.AddImplicitRequiredValidator = false);

我不想更改任何现有数据注释的行为,所以这就是我添加的全部内容