Freewind
Freewind

Reputation: 198188

How can I combine 2 validators together in play2?

For example, I want a input should be nonEmptyText and email.

If the user doesn't input anything, it will show error message The field is required, if user inputs an invalid email, it will show Invalid email.

But I found, I can just use one:

val loginForm = Form("email"->nonEmptyText)

or:

val loginForm = Form("email"->email)

For the later one, if user doesn't input, it will still show Invalid email, which is not what I want.

UPDATE1

I tried Julien's answer:

val loginForm = Form("email" -> (email verifying nonEmpty))

When user inputs nothing, the error message will be:

Valid email required, This field is required

Looks like play combines two error messages of email and nonEmpty together, but this is not exactly what I want. I hope when user not input, the message is only:

This field is required

Not:

Valid email required, This field is required

UPDATE2

I found the reason why it display combined errors is in the helper.twitterBootstrapFieldConstructor.scala.html, there is:

<span class="help-inline">@elements.errors(elements.lang).mkString(",")</span>

It combines all the errors with ,.

For my case, it should be:

<span class="help-inline">@elements.errors(elements.lang).lastOption</span>

Here, lastOption is for nonEmpty.

But I think headOption is better, but:

val loginForm = Form("email" -> (nonEmptyText verifying email))

Doesn't work -- there is no constraint of email, so we have to defined one for myself?

Upvotes: 1

Views: 715

Answers (1)

Julien Richard-Foy
Julien Richard-Foy

Reputation: 9663

According to the Form documentation, you can add constraints to a mapping using the verifying method. There are a few constraints already defined in the Constraints object. So you can write:

val loginForm = Form("email" -> (email verifying nonEmpty))

Upvotes: 2

Related Questions