2013-01-21 19 views
0

我有一組電話號碼,並不是每個人都有這些號碼中的每一個。我怎麼可以指定任何三個被滿足是不夠好:如何說我想要應用三種FluentValidation規則中的一種?

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

建立一個自定義的驗證,在模式本身需要,而不僅僅是一個屬性就可以了:http://fluentvalidation.codeplex.com/wikipage?title=Custom

+0

是否有可能在該自定義驗證程序中使用Fluent規則> E.g.我可以在那裏傳輸我的單個電話號碼規則,只是編碼決定只是調用一個? – ProfK

+0

準確地說 - 而不是'RuleFor'你會有'Custom(ValidatePhoneNumbers)',其中'ValidatePhoneNumbers'將模型作爲參數並且對3個數字執行驗證。如果驗證成功,則返回null或包含您的自定義消息的「ValidationFailure」。 – levelnis

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

+0

我不知道你的例子應該做什麼。所有物業的邏輯意味着什麼? – ProfK

+0

我編輯我的代碼,看看! –

+0

我唯一的疑問就是規則是爲'PhoneHome'定義的。那會有什麼影響? – ProfK

2

您應該使用業務規則引擎和停車難在主代碼編碼邏輯。 MS MVC的驗證框架從長遠來看會導致更多的問題,而不是解決問題。例如,你的這個規則明天可以改變。您必須重新構建並重新部署整個應用程序才能更改一條簡單的規則。

我發佈這個知道我會從MVC頑固派獲得很多噓聲和降級。

+1

哈哈,雖然我沒有噓聲,只是一個upvote。對於我來說,使用MVC的Fluent Validation對於使用適當的規則引擎有點步驟;它具有令人難以置信的可擴展性。向完整規則引擎邁出的一步是Fluent驗證規則方法,可從外部源讀取規則數據。 – ProfK

+0

我對你所說的「業務規則引擎」感興趣。你有沒有推薦使用mvc3/4前端? –

+0

@GrayKing MS Workflow Foundation有一個很棒的BRE,可以在任何.NET環境中使用(http://msdn.microsoft.com/zh-cn/vstudio/jj684582.aspx)如果您有BizTalk許可證,請看一下在其BRE(http://www.microsoft.com/biztalk/en/us/default.aspx)如果您需要一個可靠的基於Web的用戶界面,然後看看WebRule(http://rule.codeeffects.com)希望這可以幫助。 – Kizz

相關問題