0

我需要添加字母数字字段,因为我正在尝试这段代码

object TestValidation {
  implicit val readTestUser: Reads[TestValidation] = (
    (JsPath \ "firstName").read(minLength[String](1)) and
    (JsPath \ "lastName").read(minLength[String](1)) and
    (JsPath \ "email").read(email) and
    (JsPath \ "password").read(minLength[String](1)))(TestValidation.apply _)

我希望“密码”字段是字母数字我已经添加了这个自定义验证约束现在我想在 json 的 Reads 方法中集成这个可能做这样的事情

 (JsPath \ "password").read(minLength[String](1)).passwordCheckConstraint

我不知道这样做的正确方法是约束代码

val allNumbers = """\d*""".r
val allLetters = """[A-Za-z]*""".r
val passwordCheckConstraint: Constraint[String] = Constraint("constraints.passwordcheck")({
  plainText =>
    val errors = plainText match {
      case allNumbers() => Seq(ValidationError("Password is all numbers"))
      case allLetters() => Seq(ValidationError("Password is all letters"))
      case _ => Nil
    }
    if (errors.isEmpty) {
      Valid
    } else {
      Invalid(errors)
    }
})

请帮忙

4

1 回答 1

0

将约束表示为类型通常是一种非常好的做法:

import play.api.data.validation._
import play.api.libs.json._

class Password private(val str: String)

object Password {

  val passwordCheckConstraint: Constraint[String] = Constraint("constraints.passwordcheck")({
    plainText =>
      val allNumbers = """\d*""".r
      val allLetters = """[A-Za-z]*""".r
      val lengthErrors = Constraints.minLength(1).apply(plainText) match {
        case Invalid(errors) => errors
        case _ => Nil
      }
      val patternErrors: Seq[ValidationError] = plainText match {
        case allNumbers() => Seq(ValidationError("Password is all numbers"))
        case allLetters() => Seq(ValidationError("Password is all letters"))
        case _ => Nil
      }

      val allErrors = lengthErrors ++ patternErrors

      if (allErrors.isEmpty) {
        Valid
      } else {
        Invalid(allErrors)
      }
  })

  def validate(pass: String): Either[Seq[ValidationError],Password] = {
    passwordCheckConstraint.apply(pass) match {
      case Valid => Right(new Password(pass))
      case Invalid(errors) => Left(errors)
    }
  }

  implicit val format: Format[Password] = Format[Password](
    Reads[Password](jsv => jsv.validate[String].map(validate).flatMap {
      case Right(pass) => JsSuccess(pass)
      case Left(errors) => JsError(Seq((JsPath \ 'password,errors)))
    }),
    Writes[Password](pass => Json.toJson(pass.str))
  )
}

现在有了这些,您可以编写:

    (JsPath \ 'password).read[Password] //return Password instance or errors
    //or if you want to stick with the String type you can write this: 
    (JsPath \ 'password).read[Password].map(_.str)

请注意,play-json'JsPath.read方法只接受一个类型参数,并且与 html 表单验证不同。

于 2017-05-27T21:30:08.417 回答