1

如何在Play Framework 2.2.1中声明可本地化的表单验证消息,包括需要参数的消息?可本地化的表单验证消息

例如,考虑到这些本地化的消息在conf/messages

password.tooShort="Password needs at least {0} characters." 
password.doNotMatch="Passwords don't match." 

和一个表单定义是这样的:

val minLength = 8 
val changePasswordForm = Form (
    Password -> 
    tuple(
     Password1 -> nonEmptyText.verifying("password.tooShort", p => p.length() >= minLength), 
     Password2 -> nonEmptyText 
    ).verifying("password.doNotMatch", passwords => passwords._1 == passwords._2) 
) 

如何能在第一场(密码1)确认消息中声明一种适当的参数将被使用的方式(minLength)?

的形式定义调用verifying,只接受字符串的邮件不带参数:

def verifying(error: => String, constraint: (T => Boolean)): Mapping[T] = { 
    verifying(Constraint { t: T => 
    if (constraint(t)) Valid else Invalid(Seq(ValidationError(error))) 
    }) 
} 

此外,格式定义过程中调用消息()不起作用,因为它会导致默认语言被使用,而不是的每个请求的语言。

回答

0

如果您在minLength验证器中使用该版本,这可以为您提供开箱即用的功能。如果你真的想重新实现它,检查如何实现默认的,包含Play的来源,所以你已经把它们放在你的硬盘上。您可以在YOUR_PLAY_INSTALLATION/framework/src/play/src/main/scala/play/api/data/validation/Validation.scala

2

表单定义中调用play.api.i18n.Messages不起作用,因为没有play.api.i18n.Lang对象在范围上找到验证逻辑构建。将表单定义从val更改为def,并为Lang对象添加隐式方法参数。

val minLength = 8 
def changePasswordForm(implicit lang: play.api.i18n.Lang) = Form (
    Password -> 
    tuple(
     Password1 -> nonEmptyText.verifying(Messages("password.tooShort",minLength), p => p.length() >= minLength), 
     Password2 -> nonEmptyText 
    ).verifying(Messages("password.doNotMatch"), passwords => passwords._1 == passwords._2) 
) 

您需要在控制器操作中将此表单定义与范围内的隐式请求一起使用。该请求将自动提供Lang对象。

实施例:

def myAction = Action { implicit request => 
    Ok(html.myFormPage(changePasswordForm)) 
}