播放2.3 scala如何自定义约束消息



我创建了带有约束的form in play框架:

val voucherForm = Form(
  mapping(
    "voucherName" -> nonEmptyText,
    "voucherCode" -> optional(text(minLength = 6).verifying(pattern("""[a-zA-Z0-9]+""".r, error = "...")))     
  )(VoucherForm.apply)(VoucherForm.unapply)
)

当我在网页上显示此表单时,我在输入框附近显示约束消息(如Required, Minimum length: 6, constraint.pattern)。

我想自定义每个输入字段的约束消息(即相同形式的两个nonEmptyText约束将具有不同的约束消息)。我怎么能做到呢?

不使用nonEmptyText,您可以不使用text,并将您的自定义消息放在verifying中,沿着以下行:

val voucherForm = Form(
  mapping(
    "voucherName" -> text.verifying(
      "Please specify a voucher name", f => f.trim!=""),
...

这些消息取自消息。您可以创建自定义消息文件,并将自定义文本放在其中。浏览源代码,检查要放在那里的是什么有效字符串。

例如nonEmptyText的声明如下:

val nonEmptyText: Mapping[String] = text verifying Constraints.nonEmpty

,从那里,Constraints.nonEmpty看起来像这样:

  def nonEmpty: Constraint[String] = Constraint[String]("constraint.required") { o =>
    if (o == null) Invalid(ValidationError("error.required")) else if (o.trim.isEmpty) Invalid(ValidationError("error.required")) else Valid
  }

所以错误字符串是"error.required"

现在你可以在conf目录下创建一个文件messages,并在其中添加一行

error.required=This field is required

ValidationErrorapply方法声明如下:

def apply(message: String, args: Any*)

这意味着你也可以在那里传递参数,在messages中你可以使用{arg_num}语法访问它们

例如,如果你创建了这样的错误

val format = ???
ValidationError("error.time", someFormat)

将返回一个有界表单,然后play将使用MessagesApi查找名为"错误"的消息。并相应地格式化,例如,您可以创建这样的消息:

error.time=Expected time format is {0}

我的想法是有一个自定义的消息为每个字段是一个自定义的方法,像这样:

  def nonEmptyTextWithError(error: String): Mapping[String] = {
    Forms.text verifying Constraint[String]("constraint.required") { o =>
      if (o == null) Invalid(ValidationError(error)) else if (o.trim.isEmpty) Invalid(ValidationError(error)) else Valid
    }
  }

可能不是一个理想的解决方案,如果你想使用许多子约束。

最新更新