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

我想要的“密码”字段是字母数字 我已经加入此自定义的验证约束现在我想intregate此期间读取JSON的方法做这样的事情也许

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

请帮助表示类型

回答

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-jsonJsPath.read方法只接受单一类型参数,并且与html表单验证方法不同纳秒。

相关问题