如何在 PlayFramework 中检查给定字段是否为字母数字

how to check whether the given field is alphanumeric or not in PlayFramework

我必须检查密码字段是否为字母数字,如果不是,它将抛出自定义验证错误我正在使用播放框架但出现编译时错误

value checkAlphanumeric is not a member of 
     play.api.libs.json.Reads[String]
    - value checkAlphanumeric is not a member of 
     play.api.libs.json.Reads[String]

我无法达到我想要的结果我做错了这就是为什么我需要这里的代码

case class userUserSignUpValidation(firstName: String,
                                      lastName: String,
                                      email: String,
                                      password: String) extends Serializable

object UserSignUpValidation {
  val allNumbers = """\d*""".r
  val allLetters = """[A-Za-z]*""".r
  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)checkAlphanumeric))(UserSignUpValidation.apply _)
    def checkAlphanumeric(password:String)={
        val allNumbers = """\d*""".r
        val allLetters = """[A-Za-z]*""".r

        val errors = password match {
          case allNumbers() => Seq(ValidationError("Password is all numbers"))
          case allLetters() => Seq(ValidationError("Password is all letters"))
          case _ => Nil
        }
     }

我在这一行收到错误

(JsPath \ "password").read(minLength[String](8)checkAlphanumeric))(UserSignUpValidation.apply _)

实现上述场景的正确方法是什么

好吧,我想知道你为什么不 运行 在案例 class 内进行验证?

case class userUserSignUpValidation(firstName: String,
                                      lastName: String,
                                      email: String,
                                      password: String) {

   assert(!password.matches("""[A-Za-z]*""") && !password.matches("""\d*"""), "Invalid password")
   // have other field validations here
}

并且在您的 UserSignUpValidation 中使用这样的隐式格式化程序:

object UserSignUpValidation {
   implicit val userFormatter = JSON.format[userUserSignUpValidation]

    // de-serialization code here
}

你的问题是你不能那样使用你的 checkAlphanumeric 方法。您可能想要的是 Reads 上的过滤器,因此我建议您执行以下操作(我使用预先存在的方法更改了检查的实现):

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