我需要在播放中添加字母数字字段,因为我正在尝试此代码
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方法中对此进行intregate这样做可能
(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 :(得分: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
的{{1}}方法只接受单个类型参数,并且与html表单验证不同。