0

我有一些表單域,如電話號碼和郵政編碼,可以留空。但是,當他們填寫完畢後,我希望他們遵守嚴格的格式規則。Fluent驗證 - 潛在空值的條件驗證

我期待使用流利的驗證了這個任務,但我還沒有找到任何可以做到以下幾點:現在這兩個扔未設置爲實例的「對象引用

RuleFor(x => x.PhoneNumber) 
    .Matches(@"^\d{3}-\d{3}-\d{4}$") 
    .When(x => x.PhoneNumber.Length != 0) 
    .WithMessage("Phone number must be a valid 10-digit phone number with dashes, in the form of “123-456-7890”") 
    .Length(12, 12).When(x => x.PhoneNumber.Length >= 1).WithMessage("Phone number must be in the form of “123-456-7890”"); 

的一個對象。「錯誤。

我有任何意義,或者這是不可能與FluentValidation?

+0

你'。 Length()'和相關的'.When()'甚至沒有必要 - 它已經被正則表達式覆蓋了,它需要12個字符。我認爲與'.Matches()'相關聯的'.When()'也是不必要的,因爲如果值爲空,則不評估正則表達式。 –

回答

2

我認爲當您嘗試在空值爲PhoneNumber時,嘗試評估其屬性爲「對象引用未設置爲對象的實例」。首先,您需要檢查它是否爲空,然後才能應用所有其他規則。除了您在Matches(@"^\d{3}-\d{3}-\d{4}$")使用的正則表達式已經包括長度確認,所以你可以安全地刪除

.Length(12, 12).When(x => x.PhoneNumber.Length >= 1).WithMessage("Phone number must be in the form of “123-456-7890”"); 

如果刪除長度規則,這樣的事情應該工作:

When(x => x.PhoneNumber != null, 
    () => { 
     RuleFor(x => x.PhoneNumber).Matches(@"^\d{3}-\d{3}-\d{4}$") 
     .WithMessage("Phone number must be a valid 10-digit phone number with dashes, in the form of “123-456-7890”");   
}); 
+0

這兩個規則如何衝突?他們都處理12個字符。正則表達式檢查### - ### - ####模式,而長度只檢查12個字符的精確長度。 –

+0

你是對的我錯過了正則表達式中的破折號。更新了答案 –

+0

我的解決方案沒有工作嗎? –