问题
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 ValidationError
like 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