我在我的项目中使用了Fluent Validation。
在我的ViewModel中,我有一个字符串类型的属性,有效值只能是代表正整数的字符串。
因此,我创建了一个简单的IntegerValidator
来检查字符串是否可以解析为整数。这是可行的。
问题是,如何添加必须为正整数的规则?我希望使用现有的Greater Than Validator,但是将其链接到我的string属性的规则会将其作为string
进行比较,而不是作为解析后的int
。如何做到这一点?
我想做的示例(请注意ToInt()
):
RuleFor(x => x.BatchNumber).SetValidator(new IntegerValidator())
.ToInt().GreaterThan(0);
发布于 2011-11-15 21:52:34
你可以随时使用自定义方法...
RuleFor(x=>x.BatchNumber).Must(BeAPositiveIntegerString);
private bool BeAPositiveIntegerString(string batchNumber)
{
// check both parse ability and greater than (once parsed)
}
可重用性较低,但可以工作……
https://stackoverflow.com/questions/8133987
复制相似问题