How to create a Playframework 2.0 form with prerequisite?

Say I want to have a form with a field, email, which is only required if they have not inserted their phone number. Also, a phone number is only required if they did not send their email address, how would I do it?

I would like to do something like this if necessary NoValid exists.

import play.api.data._ import play.api.data.Forms._ import play.api.data.validation.Constraints._ case class User(email: Option[String] = None, age: Option[Int]) val userForm = Form( mapping( "email" -> email.verifying(requiredNoValid(phoneNumber)), "phoneNumber" -> number.verifying(requiredNoValid(email)) )(User.apply)(User.unapply) ) 

I created my own solution for this in Play 1.X, but I would like to give up most of this and use the Play 2 forms to do this for me if there is functionality or if there is a way to do this by implementing Validator or Constraint.

+8
scala validation playframework
source share
2 answers

You can also add verifying to several fields. For a simple example:

 val userForm = Form( mapping( "email" -> optional(email), "phoneNumber" -> optional(number) ) verifying("You must provide your email or phone number.", { case (e, p) => isValidEmail(e) || isValidPhoneNumber(p) })(User.apply)(User.unapply) ) 

Inside the external check, you now have access to your email and phone number, and you can cross-validate.

+7
source share

This is a solution for Java, but I'm sure you could do something similar if you use scala. You can get the data of a related form after submitting and checking it. If this is not valid, you may reject the form with some error message. For example:

 //Get filled form Form<User> filledForm = userForm.bindFromRequest(); //Get the user object User u = filledForm.get(); //If both are not empty if(u.phoneNumber.isEmpty() && u.email.isEmpty()){ filledForm.reject("email", "You must provide a valid email or phone number"); } 
+6
source share

All Articles