Skip to content

Instantly share code, notes, and snippets.

@ruimo
Created July 17, 2014 23:50
Show Gist options
  • Save ruimo/34967bea0526cdc9a533 to your computer and use it in GitHub Desktop.
Save ruimo/34967bea0526cdc9a533 to your computer and use it in GitHub Desktop.
ConstraintFormat.pattern alternative
package helpers
import play.api.libs.json.Reads
import play.api.data.validation.ValidationError
import play.api.libs.json.JsError
import play.api.libs.json.JsSuccess
// Use instead of ConstraintFormat.pattern
object JsConstraints {
def regex(r: => scala.util.matching.Regex, error: String = "error.pattern")(implicit reads: Reads[String]) =
Reads[String](js => reads.reads(js).flatMap { o =>
r.unapplySeq(o).map(_ => JsSuccess(o)).getOrElse(JsError(ValidationError(error, r)))
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment