问题摘要: 是否可以在针对特定模型解析流畅验证器时清除模型状态中的错误列表?这样流畅的验证会覆盖数据注释模型提供程序中的默认行为,而不是对它进行补充吗?
我正在使用这样的流畅验证:
FluentValidationModelValidatorProvider.Configure(
_ =>
{
// This does not seem to work, or i am misunderstanding it?
_.AddImplicitRequiredValidator = false;
});
我使用autofac作为容器,但流畅的验证实际上并没有使用容器。我把它配置如上。
我有一个这样的模型:
[Validator(typeof(PartyModelValidator))]
public class PartyModel
{
验证器验证如下......
public class PartyModelValidator : AbstractValidator<PartyModel>
{
/// <summary>
/// Initialises a new instance of the <see cref="PartyModelValidator"/> class.
/// </summary>
public PartyModelValidator()
{
this.RuleFor(_ => _.Client)
.SetValidator(new ClientValidator())
.When(_ => _.SelectedPartyTab == PartyType.Person);
this.RuleFor(_ => _.Organisation)
.SetValidator(new OrganisationValidator())
.When(_ => _.SelectedPartyTab == PartyType.Organisation);
除了某些人员和组织对象上有[Required]
个属性外,验证工作正常。
这些[Required]
属性显示为验证错误。即使整个对象实际上为空,我也会收到这些错误。
当如上配置特定的流利验证器时,如何获得流畅的验证以忽略数据注释属性?我更愿意在对象上留下注释,因为除了视图验证之外它们还可以用于其他目的吗?
答案 0 :(得分:1)
这就是诀窍,万一其他人需要代码,就在这里。
/// <summary>
/// The fluent validation model validator provider ex.
/// </summary>
internal class FluentValidationModelValidatorProviderEx : FluentValidationModelValidatorProvider
{
/// <summary>
/// Initialises a new instance of the <see cref="FluentValidationModelValidatorProviderEx"/> class.
/// </summary>
/// <param name="validatorFactory">
/// The validator factory.
/// </param>
public FluentValidationModelValidatorProviderEx(IValidatorFactory validatorFactory) : base(validatorFactory)
{
}
/// <summary>
/// get the fluent validators.
/// </summary>
/// <param name="metadata">The metadata.</param>
/// <param name="context">The context.</param>
/// <returns>the set of validators, if any validators are resolved.</returns>
/// <remarks>If the fluent validator(s) are supplied, then clear the current set of model errors.</remarks>
public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
{
var validators = base.GetValidators(metadata, context);
var modelValidators = validators as ModelValidator[] ?? validators.ToArray();
if (modelValidators.Any())
context.Controller.ViewData.ModelState.Clear();
return modelValidators;
}
/// <summary>
/// configure fluent validation.
/// </summary>
/// <param name="configurationExpression">The configuration expression.</param>
internal static void ConfigureFluentValidation(Action<FluentValidationModelValidatorProvider> configurationExpression = null)
{
configurationExpression = configurationExpression ?? (Action<FluentValidationModelValidatorProvider>)(param0 => { });
FluentValidationModelValidatorProvider validatorProvider = new FluentValidationModelValidatorProviderEx((IValidatorFactory)null);
configurationExpression(validatorProvider);
DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes = false;
ModelValidatorProviders.Providers.Add((ModelValidatorProvider)validatorProvider);
}
}