Validation 手动验证文本
我想验证从ajax请求接收的文本(JSON)Validation 手动验证文本,validation,scala,playframework,playframework-2.2,Validation,Scala,Playframework,Playframework 2.2,我想验证从ajax请求接收的文本(JSON) val myValidation: Mapping[String] = ///... def setNewNameAjax = Action { request => val json = Json parse request.body.asJson.get.toString val name = (json \ "name").toString() // how do I manually validate "name" by
val myValidation: Mapping[String] = ///...
def setNewNameAjax = Action { request =>
val json = Json parse request.body.asJson.get.toString
val name = (json \ "name").toString()
// how do I manually validate "name" by myValidation?
}
因此,目标是使用我的验证器验证name
。并且,优选地,在验证错误的情况下明智地返回结果。我该怎么做
目标不是特别验证JSON。我们的目标是使用自定义vaditor验证任何类型的文本(在本例中,它是
myValidation
)。根据映射进行验证实际上是个坏主意。应使用映射
来处理表单字段,它要求验证的是映射[String,String]
但是,您可以使用映射[T]
验证值。只是有点棘手。一般来说,我建议使用Constraint[String]
验证String
值,但下面是工作代码:
val myValidation: Mapping[String] = ///...
def setNewNameAjax = Action { request =>
val json = Json parse request.body.asJson.get.toString
val name = (json \ "name").toString()
//one mapping may have multiple constraints, so run the validation for all of them and collect the list of ValidationResults
val validationResults = myValidation.constraints.map(_(name))
//filter the list - leave only the conditions that failed
val failedValidationResults = validationResults.filter(_.isInstanceOf[Invalid])
failedValidationResults match {
case Nil => //Validation OK, no constraints failed
case _ => //Validation failed, assemble the message and inform the user
}
}
如果是纯文本或xml,是否也可以这样做?如果不是,那就不是我想要的。有两个条件:使用myValidation:Mapping[T]和不特别使用JSON。好吧,我误解了你的问题。我编辑了这篇文章来匹配你的评论谢谢<代码>一般来说,我建议使用约束[String]
-但是如何通过myConstraint.map(…)?通过myConstraint(…)
或myConstraint.apply(…)