你可以設置一個屬性進行驗證,並使用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
是否有可能在該自定義驗證程序中使用Fluent規則> E.g.我可以在那裏傳輸我的單個電話號碼規則,只是編碼決定只是調用一個? – ProfK
準確地說 - 而不是'RuleFor'你會有'Custom(ValidatePhoneNumbers)',其中'ValidatePhoneNumbers'將模型作爲參數並且對3個數字執行驗證。如果驗證成功,則返回null或包含您的自定義消息的「ValidationFailure」。 – levelnis