kgx
kgx

Reputation: 1195

Field-specific error messages in Play Framework/Scala forms

I want to customize the default error message "This field is required" when using the "nonEmptyText" constaint in the Scala form helper.

Here is an example that I want to customize:

  val form = Form(
    tuple("email" -> nonEmptyText, "password" -> nonEmptyText)
      verifying ("Invalid email or password.", result => result match {
        case (email, password) => {
          User.authenticate(email, password).isDefined
        }
      }))

Optimally in my conf/messages file I could provide a field-specific error:

error.email.required=Enter your login email address
error.password.required=You must provide a password

But in the worst case I would be happy with a wildcard message using the field name:

error.required=%s is required  
#would evaluate to "password is required", which I would then want to capitalize

I saw this %s expression in some Play 1.x documentation but it does not seem to work anymore.

Thank you in advance for your help!

Upvotes: 7

Views: 4232

Answers (1)

Fynn
Fynn

Reputation: 4873

Try to drop the usage of a nonEmptyText and use a simple text field with a custom validation:

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

You can then move a step further and exchange the String inside the verifying clause for a call to the play.api.i18n.Messages object:

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

Note that this is untested code, but it should point out the direction.

Good Luck

Upvotes: 8

Related Questions