Play form verification

2019-09-04 22:50发布

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条回答
何必那么认真
2楼-- · 2019-09-04 23:28

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

查看更多
登录 后发表回答