我有一组电话号码,并不是每个人都有这些号码中的一个。如何指定满足的三个中的任何一个都足够好:
RuleFor(p => p.PhoneHome).Matches(Regexes.TenDigitsOnly).WithMessage("Phone numbers must have only ten digits.");
RuleFor(p => p.PhoneWork).Matches(Regexes.TenDigitsOnly).WithMessage("Phone numbers must have only ten digits.");
RuleFor(p => p.PhoneCell).Matches(Regexes.TenDigitsOnly).WithMessage("Phone numbers must have only ten digits.");
答案 0 :(得分:1)
您可以为验证设置属性,并使用Must
方法应用它。
RuleFor(p => p.PhoneHome)
.Matches(Regexes.TenDigitsOnly).WithMessage("Phone numbers must have only ten digits.")
.Must((person, phone) => ValidatePhones(person, phone))..WithMessage("Please add a phone number.");
RuleFor(p => p.PhoneWork)
.Matches(Regexes.TenDigitsOnly).WithMessage("Phone numbers must have only ten digits.")
.Must((person, phone) => ValidatePhones(person, phone))..WithMessage("Please add a phone number.");
RuleFor(p => p.PhoneCell)
.Matches(Regexes.TenDigitsOnly).WithMessage("Phone numbers must have only ten digits.")
.Must((person, phone) => ValidatePhones(person, phone))..WithMessage("Please add a phone number.");
private bool ValidatePhones(Person person, string phone) {
return !string.IsNullOrEmpty(person.PhoneHome) || !string.IsNullOrEmpty(person.PhoneWork) || !string.IsNullOrEmpty(PhoneCell);
}
查看自定义验证: http://fluentvalidation.codeplex.com/wikipage?title=Custom
答案 1 :(得分:1)
您应该使用业务规则引擎并停止主代码中的硬编码逻辑。从长远来看,MS MVC的验证框架会导致更多的问题。例如,你的这条规则明天肯定会改变。您将不得不重建和重新部署整个应用程序,以便只更改一个简单的规则。
我发布这个消息知道我将从MVC顽固分子中获得大量的助推器和降级。
答案 2 :(得分:0)
设置一个自定义验证器,它接受模型本身,而不仅仅是其上的属性:http://fluentvalidation.codeplex.com/wikipage?title=Custom