简体   繁体   中英

How to display global errors of a form in different inputs?

I have a form for logging:

val loginForm = Form(tuple(
    "email" -> (nonEmptyText verifying email.constraints.head),
    "password" -> nonEmptyText
  )
   .verifying("Email doesn't exist", params => User.findByEmail(params._1) != None)
   .verifying("Password incorrect", params => 
       User.findByEmail(params._1).map(_.checkPassword(params._2)) == Some(true))
)

Notice there two global validators in the last. They should be performed only if email is not empty and has valid format, and password is not empty, so I put the in global.

I want to display Email doesn't exist beside email input, and Password incorrect beside password input, how to do that in view?

At present, I use loginForm.globalError , but it will show both of them beside one input.

@inputText(loginForm("email"), '_label->"Email:",
    '_error->loginForm.globalError
)
@inputPassword(loginForm("password"), '_label->"Password:")

IMHO, the global error should stay global, so I'd put it above your inputs:

@loginForm.globalError.map { error =>
  <div>@error</div>
}
@inputText(loginForm("email"), '_label->"Email:")
@inputPassword(loginForm("password"), '_label->"Password:")

Otherwise you'd have to do something like this:

'_error -> loginForm.error("email").orElse(globalError)

I think the email constraint should be defined on the email field rather than globally. And think it makes sense for the password constraint to be global since it checks the pair (email, password).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM