how to add custom ValidationError in Json Reads in PlayFramework

放肆的年华 提交于 2021-02-08 05:35:10

问题


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


回答1:


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)



回答2:


ValidationError messages are supposed to be keys to be used for translation, not human readable messages.

However, if you still want to change the message for minLength, you'll need to reimplement it, since it is hard-coded.

Thankfully, the source code is available, so you can easily change it as you please:

def minLength[M](m: Int)(implicit reads: Reads[M], p: M => scala.collection.TraversableLike[_, M]) =
  filterNot[M](JsonValidationError("error.minLength", m))(_.size < m)

If you want to use a more generic pattern to specify errors, the only access you have is using the result from your validation. For instance, you could do

val json: JsValue = ???
json.validate[DirectUserSignUpValidation] match {
  case JsSuccess(dusuv, _) => doSomethingWith(dusuv)
  case JsError(errs) => doSomethingWithErrors(errs)
}

Or, with a more compact approach

json.validate[DirectUserSignUpValidation].
  fold(doSomethingWithErrors, doSomethingWith)


来源:https://stackoverflow.com/questions/44255681/how-to-add-custom-validationerror-in-json-reads-in-playframework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!