.Net core Fluent validation accept empty 或 accept with given precision

.Net core Fluent validation accept empty or accept with given precision

您好,我正在尝试使用流畅的验证来验证 .Net 核心中的一个小数字段。该字段可以为空,或者如果存在值,则它应该匹配精度 4,1。目前我已经试过了

this.RuleFor(x => x.MastHeight).NotNull().ScalePrecision(1, 4).When( x => x.MastHeight).NotEmpty();

以上代码不正确。我正在尝试执行以下规则的验证

  1. Mast height cannot be null
  2. Mast height may take empty
  3. Mast height can take zero
  4. If values present in mast height then it should follow precision 1,4

有人可以帮我编写包含上述规则的正确验证吗?任何帮助将不胜感激。谢谢

试试这个:

    RuleFor(p => p.MastHeight)
        .ScalePrecision(1, 4)
        .When(p => p.MastHeight != decimal.Zero && p.MastHeight.HasValue);

你不需要 .When( x => x.MastHeight).NotEmpty() - 它甚至不会编译 -

ScalePrecision(1,4) 表示您总共允许 4 位数字和 1 位小数,因此它将接受零(空小数点)而无需特殊规则。

public class MyType {
    public decimal? MastHeight { get; set; }
    public MyType(decimal? mastHeight) {
        MastHeight = mastHeight;
    }
}

public class MyTypeValidator : AbstractValidator<MyType> {
    public MyTypeValidator() {
        RuleFor(x => x.MastHeight).NotNull().ScalePrecision(1, 4);
    }
}

[Fact]
public void Decimal_Validation_Valid() {
    var decimals = new MyType[] {
        new MyType(default(decimal)),
        new MyType(1m),
        new MyType(1234m),
        new MyType(1.4m),
        new MyType(321.4m),
    };

    var validator = new MyTypeValidator();

    foreach (var value in decimals) {
        var validationResult = validator.Validate(value);
        Assert.True(validationResult.IsValid);
    }
}

[Fact]
public void Decimal_Validation_Invalid() {
    var decimals = new MyType[] {
        new MyType(null),
        new MyType(1.42m),
        new MyType(1111.4m),
    };

    var validator = new MyTypeValidator();

    foreach (var value in decimals) {
        var validationResult = validator.Validate(value);
        Assert.False(validationResult.IsValid);
    }
}