Daniel Hilgarth
Daniel Hilgarth

Reputation: 174427

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

Upvotes: 5

Views: 1153

Answers (1)

drharris
drharris

Reputation: 11214

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...

Upvotes: 1

Related Questions