3

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

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]

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

4

2 回答 2

5

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

(JsPath \ "firstName").read[String].filter(ValidationError("your.error.message"))(_.length > 0)
于 2017-05-30T13:15:12.173 回答
2

ValidationError消息应该是用于翻译的键,而不是人类可读的消息。

但是,如果您仍想更改 的消息minLength,则需要重新实现它,因为它是硬编码的。

值得庆幸的是,源代码是可用的,所以您可以轻松地随意更改它:

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

如果您想使用更通用的模式来指定错误,您唯一的访问权限是使用验证的结果。例如,你可以做

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

或者,使用更紧凑的方法

json.validate[DirectUserSignUpValidation].
  fold(doSomethingWithErrors, doSomethingWith)
于 2017-05-30T07:32:27.867 回答