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表單驗證方法不同納秒。

相關問題