【问题标题】:Fluent validation rule uppers without corresponding rule流利的验证规则上界没有对应的规则
【发布时间】:2012-08-17 11:44:49
【问题描述】:

我有一个奇怪的问题。 ModelState 有错误。但我对此没有规定。没有过滤器,验证器文件中没有规则。

我的代码。视图模型:

[Validator(typeof(TestValidation))]
public class PayerPayRateViewModel 
{

    public int TestId { get; set; }

    public bool AllServices { get; set; }

    public int ParentEntityId { get; set; }
}

验证器

 public class TestValidation : BaseEntityRepositoryValidator<Core.Domain.Model.Entities.Payer, PayerPayRateViewModel>
{
    public TestValidation()
    {
        RuleFor(x => x.ParentEntityId).Must(CheckUniqueService);
    }

    protected bool CheckUniqueService(PayerPayRateViewModel model, int value)
    {
        if (model.AllServices)
        {
            return true;
        }

        return false;          
    }      
}

如果我有值为 0 的 TestId,我会得到“TestId: Field is required”。

当我从 Viewmodel 类中删除验证属性时,我收到“A value is required.”错误。

为什么会这样?

【问题讨论】:

    标签: asp.net-mvc-3 fluentvalidation


    【解决方案1】:

    因为您试图将空字符串绑定到不可为空的类型。如果您希望这种情况发生,请使用可为空的类型:

    [Validator(typeof(TestValidation))]
    public class PayerPayRateViewModel 
    {
        public int? TestId { get; set; }
    
        public bool AllServices { get; set; }
    
        public int ParentEntityId { get; set; }
    }
    

    默认情况下,有一个隐含的Required 属性应用于所有不可为空的类型(想想整数、日期时间、小数......)。

    顺便说一句,您可以禁用此默认行为:

    DataAnnotationsModelValidatorProvider
        .AddImplicitRequiredAttributeForValueTypes = false;
    

    【讨论】:

    • 达林,谢谢你的帮助。这不是你第一次回答,这保存。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 2020-06-09
    • 2016-05-13
    • 2013-06-03
    相关资源
    最近更新 更多