Play框架/ Scala表单中特定于字段的错误消息

时间:2012-10-15 23:11:17

标签: scala playframework playframework-2.0

我想在Scala表单助手中使用“nonEmptyText”constaint时自定义默认错误消息“此字段是必需的”。

以下是我想要自定义的示例:

  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

我在一些Play 1.x文档中看到了这个%s表达式,但它似乎不再起作用了。

提前感谢您的帮助!

1 个答案:

答案 0 :(得分:8)

尝试放弃使用nonEmptyText并使用简单的text字段进行自定义验证:

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

然后,您可以更进一步,在String子句中交换verifying,以便调用play.api.i18n.Messages对象:

tuple(
  "email" -> text.verifying(Messages("error.email.required"), _.isDefined),
  "password" -> text.verifying(Messages("error.password.required"), _.isDefined)
)

请注意,这是未经测试的代码,但应指出方向。

祝你好运