【问题标题】:Manually validate a text手动验证文本
【发布时间】:2014-02-10 03:14:00
【问题描述】:

我想验证从 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?
}

所以目标是使用我的验证器myValidation 验证name。并且,最好在出现验证错误的情况下明智地返回结果。我该怎么做?

我们的目标不是特别验证 JSON。目标是使用自定义 vaditor 验证任何类型的文本(在本例中为 myValidation)。

【问题讨论】:

    标签: validation scala playframework playframework-2.2


    【解决方案1】:

    根据Mapping 进行验证实际上是个坏主意。 Mapping 应该用于处理表单字段,它需要 Map[String, String] 而不仅仅是要验证的值。

    但是,您可以使用Mapping[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。
    • 好的,我误解了你的问题。我编辑了帖子以匹配您的 cmets
    • 谢谢。 In general I'd advise to validate a String value using Constraint[String] - 但是如何通过 myConstraint.map(...)?
    • 通过myConstraint(...)myConstraint.apply(...)
    猜你喜欢
    • 1970-01-01
    • 2015-11-04
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 2022-07-16
    • 1970-01-01
    • 2023-04-01
    相关资源
    最近更新 更多