Search code examples
c#fluentvalidation

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


I've started using FluentValidation on a WPF project, till now I used it in a simple way checking if a field has been filled or less then n character.

Now I've to check if the value inserted (which is a string...damn old code) is greater then 0. Is there a simple way I can convert it using

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

Thanks in advance


Solution

  • Just write a custom validator like this

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

    And from your place where you need to validate do this

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

    Update 11/8/21

    If you are going to use this on a large project or API, you are probably better by doing this from the Startup and we don't need to manually call the validator.Validate() in each and every method.

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