Angel Blanco
Angel Blanco

Reputation: 703

Play framework 2.0: Create validation error message using attribute value

Using scalaforms for the play framework, say that i have form such as:

case class User(name: String, emails: List[String])

val userForm = Form(
    mapping(
        "name" -> text,
        "emails" -> list(text).verifying("Emails are duplicated",x => SomeFunctionThatHandlesDuplicateEmails(x))
    )(User.apply, User.unapply)
  )

Where SomeFunctionThatHandlesDuplicateEmails is a function that returns false (thus, making the field invalid) if any of the emails received in the form is already in database.

Now then, my question is:

Is there a way to use the value of the validated field to create the error message? I would like to tell the user which emails in particular were duplicated, not just tell them "Emails are duplicated" as shown above.

Upvotes: 1

Views: 1102

Answers (1)

Brian Smith
Brian Smith

Reputation: 3381

verifying() takes a series of Constraint[T].

You can see examples of Constraints implemented here.

Note that the validation function in each receives the value to be validated e.g. "o" in the "min" constraint repeated below:

 def min(minValue: Int): Constraint[Int] = Constraint[Int]("constraint.min", minValue) { o =>
   if (o >= minValue) Valid else Invalid(ValidationError("error.min", minValue))
 }

This could just as easily be:

 def min(minValue: Int): Constraint[Int] = Constraint[Int]("constraint.min", minValue) { o =>
   if (o >= minValue) Valid else Invalid(ValidationError("error.min", minValue, o))
 }

which would make "o" available to the error message formatter as {1} (minValue is {0}).

Upvotes: 2

Related Questions