Search code examples
jsonscalaplayframeworkplayframework-2.5playframework-json

how to add custom ValidationError in Json Reads in PlayFramework


I am using play Reads validation helpers i want to show some custom message in case of json exception eg:length is minimum then specified or the given email is not valid , i knnow play displays the error message like this error.minLength but i want to display a reasonable message like please enter the character greater then 1 (or something ) here is my code

case class DirectUserSignUpValidation(firstName: String,
                                      lastName: String,
                                      email: String,
                                      password: String) extends Serializable

object DirectUserSignUpValidation {
  var validationErrorMsg=""
  implicit val readDirectUser: Reads[DirectUserSignUpValidation] = (
  (JsPath \ "firstName").read(minLength[String](1)) and
    (JsPath \ "lastName").read(minLength[String](1)) and
    (JsPath \ "email").read(email) and
    (JsPath \ "password").read(minLength[String](8).
      filterNot(ValidationError("Password is all numbers"))(_.forall(_.isDigit)).
      filterNot(ValidationError("Password is all letters"))(_.forall(_.isLetter))
    )) (UserSignUpValidation.apply _)
}

i have tried to add ValidationErrorlike this

 (JsPath \ "email").read(email,Seq(ValidationError("email address not correct")) and
   but its giving me compile time error


  too many arguments for method read: (t: T)play.api.libs.json.Reads[T]

please helo how can i add custom validationError messages while reading json data


Solution

  • There is no such thing as (JsPath \ "firstName").read(minLength[String](1)) in play json. what you can do with custom error message is this:

    (JsPath \ "firstName")
      .read[String]
      .filter(ValidationError("your.error.message"))(_.length > 0)