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?
我在我的项目中使用流利的验证。在我的ViewModel中,我有一个类型为string的属性,有效值只是表示正整数的字符串。因此,我创建了一个简单的IntegerValidator,它检查字符串是否可以解析为整数。这个作品。问题是,如何添加它必须是一个正整数的规则?我希望使用现有的大于Validator的值,但是将它链接到我的string属性的规则会将它作为一个字符串进行比较,而不是作为一个解析的int类型进行比较。
Sample of what I would like to do (note the ToInt()
):
我想做的样品(请注意ToInt()):
RuleFor(x => x.BatchNumber).SetValidator(new IntegerValidator())
.ToInt().GreaterThan(0);
1 个解决方案
#1
1
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...
更少的可重用性,但会起作用……
#1
1
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...
更少的可重用性,但会起作用……