How to use Play2 ConstraintReads.minLength

410 views Asked by At

I am trying to build a simple validator for incoming JSON.

I want to check that the JsObject has only one field "name" which is a non empty String.

  import play.api.libs.json.Reads._
  import play.api.libs.json._
  val myRead = ( __ \ "name" ).json.pickBranch[JsString](minLength(1))

I would expect myRead to be a Reads[JsObject] or something similar but what I get instead is a compilation error:

diverging implicit expansion for type play.api.libs.json.Reads[M] starting with method ArrayReads in trait DefaultReads

how to get rid of that problem?

1

There are 1 answers

0
mjaskowski On

Ok, turned out that minLength simply does not work with JsString.

Ended up with a following solution:

private def myPattern(regex: => Regex, error: String = "error.pattern")(implicit reads:Reads[JsString]) = 
    Reads[JsString]( js => reads.reads(js).flatMap { o =>
    regex.unapplySeq(o.as[String]).map( _ => JsSuccess(o) ).getOrElse(JsError(error))
}) 

val myRead = (__ \ "name" ).json.pickBranch[JsString](myPattern(new Regex(".+"))

works perfectly, although I miss some "standard" validations here.