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)) 
}