Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 993
advapi Avatar asked Nov 05 '19 15:11

advapi


2 Answers

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;
                })
like image 72
HariHaran Avatar answered Oct 07 '22 17:10

HariHaran


Another solution:

RuleFor(a => a.MyStringField).Must(x => int.TryParse(x, out var val) && val > 0)
.WithMessage("Invalid Number.");
like image 37
Silvestre Avatar answered Oct 07 '22 15:10

Silvestre