2016-07-19 62 views
1

內部類,負責驗證我有簡單的規則:FluentValidation修改錯誤信息

RuleFor(u => u.Id) 
    .Cascade(CascadeMode.StopOnFirstFailure) 
    .NotEmpty().WithMessage("Id is required") 
    .Must(ValidateId); 

以下是我ValidateId功能:

private bool ValidateId(CreateAccountBindingModel model, string id, PropertyValidatorContext context) 
{ 
    if (id=="test") 
    { 
     context.Rule.CurrentValidator.ErrorCodeSource = new StaticStringSource("You are testing"); 
     return false; 
    } 

    var idValid = IdValidator.IsValid(id); 
    if (!idValid) 
    { 
     context.Rule.CurrentValidator.ErrorCodeSource = new StaticStringSource("Id is invalid"); 
     return false; 
    } 
    return true; 
} 

如果我跑我的驗證,我得到默認錯誤,而不是我在我的函數中指定的自定義錯誤。
我試着使用它們設置:

context.Rule.CurrentValidator.ErrorCodeSource = new StaticStringSource("Id is invalid"); 

,但沒有任何運氣。

如何在驗證功能中定義錯誤消息?

+0

@ AlekseyL.sorry回覆這樣的遲到。我創建了擴展名,允許我爲每個規則調用'OnFailure'。我已經在FluentValidation repo中發佈了我的代碼(https://github.com/JeremySkinner/FluentValidation/issues/299#issuecomment-233904267),我正在等待Jeremy的評論。我已經在我的項目中實現了這個解決方案,並且它工作正常,但是我希望在我發佈之前獲得作者的評論。也許你可以看看它? – Misiu

+0

我認爲這與這個問題無關。 –

+0

@AlekseyL。對於那個很抱歉。我錯了問題。該鏈接是相關的http://stackoverflow.com/questions/38436630/fluentvalidation-logonfailure-override – Misiu

回答

1

可以使用MessageBuilder定義錯誤消息:

if (id == "test") 
{ 
    context.Rule.MessageBuilder = c => "You are testing"; 
    return false; 
} 
+0

謝謝你,這工作正常:) – Misiu

1

我不會實現你正在嘗試做一個自定義的驗證功能,您可以在使用FluentValidation本身做:

RuleFor(u => u.Id) 
.Cascade(CascadeMode.StopOnFirstFailure) 
.Must(x => x !="test").WithMessage("You are testing.") 
.Must(x => IdValidator.IsValid(x)).WithMessage("Id is invalid."); 
+0

我會嘗試,但在我的自定義驗證功能,我有更多的邏輯,包括日誌和數據庫訪問,博我想如果我可以從我的自定義函數設置錯誤消息,那就太好了。 – Misiu