gpt4 book ai didi

c# - Fluentvalidation 仅在填充字段时验证

转载 作者:行者123 更新时间:2023-11-30 17:28:03 27 4
gpt4 key购买 nike

我有一个小数字段,例如:

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com