簡體   English   中英

如何在播放框架中添加字母數字字段

[英]how to add alphanumeric field in play framework

我需要為此添加字母數字字段,我正在嘗試此代碼

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

我希望“ password”字段為字母數字,我已經添加了此自定義驗證約束,現在我想在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)
    }
})

請幫忙

通常將約束表示為類型是一種很好的做法:

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-jsonJsPath.read方法僅接受單個類型參數,並且與html表單驗證不同。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM