【问题标题】:Field-specific error messages in Play Framework/Scala formsPlay Framework/Scala 表单中特定于字段的错误消息
【发布时间】:2012-10-05 23:54:50
【问题描述】:

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

这是我要自定义的示例:

  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 表达式,但它似乎不再起作用了。

提前感谢您的帮助!

【问题讨论】:

    标签: scala playframework playframework-2.0


    【解决方案1】:

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

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

    然后您可以更进一步,将verifying 子句中的String 替换为对play.api.i18n.Messages 对象的调用:

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

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

    祝你好运

    【讨论】:

    • 谢谢@fynn,我会试一试的。
    • 您的代码运行良好。再次感谢您为我指明正确的方向!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2015-04-17
    • 2011-07-22
    • 2012-12-06
    • 1970-01-01
    相关资源
    最近更新 更多