Fluentvalidation仅在填充字段时验证

时间:2018-12-10 21:56:06

标签: c# asp.net fluentvalidation

我有一个十进制字段,例如:

public decimal Limit {get; set;}

现在,我正在尝试对规则进行流利验证:

This field is not mandatory but if it IS populated, then validate its greater than 0. If it isn't populated, then ignore it

我该怎么做?我的问题是,小数仍然默认为0,所以如何确定它是否填充了0?

我一直在尝试类似的东西:

When(x => x.Limit== 0, () =>
            {
                RuleFor(x => x.Limit)
                    .Empty()
                    .GreaterThan(0)
                    .WithMessage("{PropertyName} sflenlfnsle Required");
            })

谢谢

2 个答案:

答案 0 :(得分:1)

如评论中所述,区分未设置(默认值也是如此)和已设置为默认值的值类型的唯一方法是将类型更改为可空值类型。

void Main()
{

    var example1 = new SomeType();                  // Limit not set, should pass validation
    var example2 = new SomeType(){Limit = 0};       // Limit set, but illegal value, should fail validation
    var example3 = new SomeType(){Limit = 10.9m};   // Limit set to legal value, should pass validation

    var validator = new SomeTypeValidator();

    Console.WriteLine(validator.Validate(example1).IsValid);    // desired is 'true'
    Console.WriteLine(validator.Validate(example2).IsValid);    // desired is 'false'
    Console.WriteLine(validator.Validate(example3).IsValid);    // desired is 'true'
}


public class SomeType
{
    public Decimal? Limit { get; set; }
}

public class SomeTypeValidator : AbstractValidator<SomeType>
{
    public SomeTypeValidator()
    {
        RuleFor(r=>r.Limit.Value)
            .NotEmpty()
            .When(x=> x.Limit.HasValue);
    }
}

答案 1 :(得分:-1)

我认为这将满足您的需求。

public decimal Limit {get;set;}

在您的验证程序构造器中

RuleFor(x => x.Limit).Must(BeAValidDecimal).GreaterThan(0);

以及验证器中的私有验证方法

private bool BeAValidDecimal(decimal unvalidatedDecimal)
{
   if(decimal.TryParse(unvalidatedDecimal.ToString(), out decimal validatedDecimal))
   {
      return true;
   }
   else
   {
      return false;
   }
}