我想验证从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 myValidation?
}
所以目的是使用我的验证器name
验证myValidation
。并且,优选地,在验证错误的情况下合理地返回结果。我该怎么做?
目标不是特别验证JSON。目标是使用自定义vaditor验证任何类型的文本(在这种情况下,它是myValidation
)。
答案 0 :(得分:2)
对Mapping
进行验证实际上是一个坏主意。应使用Mapping
来处理表单字段,并且它需要Map[String, String]
而不是仅验证值。
但是,您可以使用Mapping[T]
验证值。这有点棘手。一般情况下,我建议使用String
验证Constraint[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
}
}