I have a set of phone numbers, and not everybody has one of each of these numbers. How can I specify that any of the three being satisfied is good enough:

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.");
有帮助吗?

解决方案 3

Set up a custom validator that takes in the Model itself rather than just a property on it: http://fluentvalidation.codeplex.com/wikipage?title=Custom

其他提示

You should use a business rules engine and stop hard coding logic in your main code. MS MVC's validation framework causes more problems in the long run than it solves. For example, this rule of yours can definitely change tomorrow. You'll have to rebuild and redeploy your entire app in order to change just one simple rule.

I'm posting this knowing that I'm going to get a lot of boos and downgrades from MVC die-hards.

You could set a property for a validation and apply it using the Must method.

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

Take a look at Custom Validations: http://fluentvalidation.codeplex.com/wikipage?title=Custom

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top