Search code examples
validationscalaplayframeworkplayframework-2.2

Manually validate a text


I want to validate a text (JSON) received from an ajax request.

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?
}

So the aim is to validate name using my validator myValidation. And, preferably, sensibly return the result in case of a validation error. How do I do this?

The goal is not to validate JSON in particular. The goal is to validate any kind of a text using a custom vaditor (in this case, it's myValidation).


Solution

  • That's actually a bad idea to validate against a Mapping. A Mapping should be used to handle a form field and it expects a Map[String, String] instead of just a value to be validated.

    However, you can validate a value using a Mapping[T]. It's just a little trickier. In general I'd advise to validate a String value using Constraint[String] but here's the working code:

    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
      }
    }