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);
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With