2012-10-15 37 views
7

我想在Scala窗體幫助器中使用「nonEmptyText」常量時,自定義默認錯誤消息「此字段是必需的」。Play Framework/Scala表單中特定於字段的錯誤消息

這裏是我要定製一個例子:

val form = Form(
    tuple("email" -> nonEmptyText, "password" -> nonEmptyText) 
     verifying ("Invalid email or password.", result => result match { 
     case (email, password) => { 
      User.authenticate(email, password).isDefined 
     } 
     })) 

最理想的在我的conf/messages文件,我可以提供一個特定的字段錯誤:

error.email.required=Enter your login email address 
error.password.required=You must provide a password 

但在最壞的情況下,我會喜歡使用字段名稱的通配符消息:

error.required=%s is required 
#would evaluate to "password is required", which I would then want to capitalize 

我看到了%s表達式一些Play 1.x文檔,但它似乎不工作了。

非常感謝您的幫助!

回答

8

嘗試刪除一個nonEmptyText的使用量和使用簡單text字段自定義驗證:

tuple(
    "email" -> text.verifying("Enter your login email address", {!_.isEmpty}), 
    "password" -> text.verifying("You must provide a password", {!_.isEmpty}) 
) 

然後,您可以動一步,並交換Stringverifying子句中,用於向通話play.api.i18n.Messages對象:

tuple(
    "email" -> text.verifying(Messages("error.email.required"), {!_.isEmpty}), 
    "password" -> text.verifying(Messages("error.password.required"), {!_.isEmpty}) 
) 

注意,這是未經測試的代碼,但它應該指出的方向。

好運

+0

感謝@fynn我給這個一杆。 – kgx

+0

你的代碼工作得很好。再次感謝您指點我正確的方向! – kgx

+0

不,問題。我很高興我能幫助... – fynn

相關問題