使用 FluentValidation 检查字符串是否为大于零的数字

Using FluentValidation to check if a string is a number greater than zero

我已经开始在一个 WPF 项目上使用 FluentValidation,直到现在我都以一种简单的方式使用它来检查字段是否已填充或少于 n 个字符。

现在我要检查插入的值(这是一个字符串...该死的旧代码)是否大于 0。有没有一种简单的方法可以使用

转换它
RuleFor(x=>x.MyStringField).Somehow().GreaterThen(0) ?

提前致谢

像这样写一个自定义验证器

public class Validator : AbstractValidator<Test>
    {
        public Validator()
        {
            RuleFor(x => x.MyString)
                .Custom((x, context) =>
                {
                    if ((!(int.TryParse(x, out int value)) || value < 0))
                    {
                        context.AddFailure($"{x} is not a valid number or less than 0");
                    }
                });
        }
    }

然后在您需要验证的地方执行此操作

var validator = new Validator();
var result = validator.Validate(test);
Console.WriteLine(result.IsValid ? $"Entered value is a number and is > 0" : "Fail");

21 年 11 月 8 日更新

如果您要在大型项目或 API 上使用它,您最好从 Startup 执行此操作,我们不需要手动调用 validator.Validate() 在每个方法中。

services.AddMvc(options => options.EnableEndpointRouting = false)
                .AddFluentValidation(fv =>
                {
    fv.RegisterValidatorsFromAssemblyContaining<BaseValidator>();
                    fv.ImplicitlyValidateChildProperties = true;
                    fv.ValidatorOptions.CascadeMode = CascadeMode.Stop;
                })

另一个解决方案:

RuleFor(a => a.MyStringField).Must(x => int.TryParse(x, out var val) && val > 0)
.WithMessage("Invalid Number.");