如何在 PlayFramework 中的 Json Reads 中添加自定义 ValidationError [英] how to add custom ValidationError in Json Reads in PlayFramework

查看:57
本文介绍了如何在 PlayFramework 中的 Json Reads 中添加自定义 ValidationError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 play Reads 验证助手,我想在 json 异常的情况下显示一些自定义消息,例如:长度是最小值,然后指定或给定的电子邮件无效,我知道 play 会显示这样的错误消息 error.minLength 但我想显示一条合理的消息,例如请输入大于 1(或其他)的字符,这是我的代码

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 _)
}

我已经尝试像这样添加ValidationError

 (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]

请教我如何在读取 json 数据时添加自定义验证错误消息

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

推荐答案

(JsPath \ "firstName").read(minLength[String](1)) 中没有这样的东西json.您可以对自定义错误消息执行以下操作:

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)

这篇关于如何在 PlayFramework 中的 Json Reads 中添加自定义 ValidationError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆