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

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");
            })


谢谢

最佳答案

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

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);
    }
}

关于c# - Fluentvalidation仅在填充字段时验证,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53714263/

10-16 23:13