Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaining rules that depend on each other

I am using Fluent Validation in my project.
In my ViewModel I have a property that is of type string, valid values are only string representing positive integers.
So, I created a simple IntegerValidator that checks whether or not the string can be parsed into an integer. This works.
Problem is, how to add the rule that it must be a positive integer? I would like to use the existing Greater Than Validator, but chaining it to the rule for my string property would compare it as a string, not as a parsed int. How to achieve this?

Sample of what I would like to do (note the ToInt()):

RuleFor(x => x.BatchNumber).SetValidator(new IntegerValidator())
                           .ToInt().GreaterThan(0);
like image 333
Daniel Hilgarth Avatar asked Nov 13 '22 14:11

Daniel Hilgarth


1 Answers

You could always use a custom method...

RuleFor(x=>x.BatchNumber).Must(BeAPositiveIntegerString);

private bool BeAPositiveIntegerString(string batchNumber)
{
    // check both parse ability and greater than (once parsed)
}

Less reusability but would work...

like image 170
drharris Avatar answered Dec 22 '22 01:12

drharris