-->

Play form verification

2019-09-04 22:56发布

问题:

How to add validation in play form?

Below is reset password form which expects user to enter password twice.

@(tokenId: String, form: Form[ResetPassword])(implicit messages: play.api.i18n.Messages, request: RequestHeader)
@main("Reset Password") {
  @helper.form(routes.Application.handleResetPassword(tokenId)) {

    @helper.inputText(form("password1"))

    @helper.inputText(form("password2"))

    <button type="submit">Submit</button>

  }

}

In above form, I would like to add validation that will check if password1 and password2 are same or not.

Thanks Pari

回答1:

You could do:

val userFormConstraintsAdHoc = Form(
  mapping(
    "password1" -> text,
    "password2" -> text
  )(UserData.apply)(UserData.unapply) verifying("Failed form constraints!", fields => fields match {
    case userData => form.password1.equals(form.password2)
  })
)

This is just untested pseudo code, check out the docs for that purpose