Incerteza
Incerteza

Reputation: 34884

Customizing the error messages for the standard validators

I have a simple form:

  val addForm = Form(
    tuple("email" -> email, "password" -> nonEmptyText)
      verifying("Invalid email or password", result => User.authenticate(result._1, result._2).isRight)
  )

The general error message above is ok. But how do I customize the specific error messages for the email and password. For now in case of empty password I've got this kind of error:

password error.required

How do I customize this error message?

UPDATE: Even this doesn't work because the validation message is still the same as it was:

val addForm = Form(
        tuple("email" -> email, "password" -> nonEmptyTextWithMessage("My message"))
          verifying("Invalid email or password", result => User.authenticate(result._1, result._2).isRight)
      )


def nonEmptyTextWithMessage(errorMessage: String): Mapping[String] = nonEmptyText.verifying(errorMessage, { _ => true })

Upvotes: 0

Views: 164

Answers (2)

S.Karthik
S.Karthik

Reputation: 1389

My colleague suggest, If you are using scala template, you could customize error message as follows

just add

'_error ->addForm("password").error.map(_.withMessage("Please provide password"))

like

 @helper.inputPassword(addForm("password"), 'class->"col-md-12", '_label ->"Password",'style->"margin-bottom:20px", '_showConstraints->false, 'placeholder->"Enter Password", '_error ->addForm("password").error.map(_.withMessage("Please provide password")))

Upvotes: 1

Manuel Bernhardt
Manuel Bernhardt

Reputation: 3140

The nonEmptyText constraint defaults to using error.required as message key. You could change that in your conf/messages file, but I suppose this is not what you want.

If you want to re-use a pre-defined Constraint (note that nonEmptyText is not a Constraint but a Mapping), you could do the following:

val addForm = Form(
  tuple(
    "email" -> email,
    "password" -> text.verifying(Constraints.nonEmpty.copy(name = Some("My message"))())
   ).verifying("Invalid email or password", result => User.authenticate(result._1, result._2).isRight)
)

It does not look very nice, but I'm not aware of any helper function that would achieve the same.

Upvotes: 1

Related Questions