Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Validation 手动验证文本_Validation_Scala_Playframework_Playframework 2.2 - Fatal编程技术网

Validation 手动验证文本

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

我想验证从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
。并且,优选地,在验证错误的情况下明智地返回结果。我该怎么做


目标不是特别验证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(…)