Skip to content

Instantly share code, notes, and snippets.

@mandubian
Forked from playxamplez-admin/CODE
Last active December 20, 2015 01:49
Show Gist options
  • Save mandubian/6051892 to your computer and use it in GitHub Desktop.
Save mandubian/6051892 to your computer and use it in GitHub Desktop.
Validate #Json with pure #JsObject #transformer #Reads #Play2.1
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 YOUR_NAME_HERE <YOUR_URL_HERE>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
import play.api.libs.json._
import play.api.data.validation._
import play.api.libs.functional.syntax._
val json = Json.obj(
"name" -> "John",
"email" -> "john.doe@company.com",
"password" -> "password",
"confirmPassword" -> "password"
)
val json2 = Json.obj(
"name" -> "John",
"email" -> "john.doe@company.com",
"password" -> "password",
"confirmPassword" -> "password2"
)
// pick json as JsObject only if password is validated
val passwordValidator =
__.json.pick[JsObject] keepAnd
(
(
(__ \ "password").read[String] and
(__ \ "confirmPassword").read[String]
).tupled.filter(ValidationError("password not confirmed")){ case(pwd, confPwd) => pwd == confPwd }
)
scala> passwordValidator.reads(json)
res8: play.api.libs.json.JsResult[play.api.libs.json.JsObject] =
JsSuccess({"name":"John","email":"john.doe@company.com","password":"password","confirmPassword":"password"},)
scala> passwordValidator.reads(json2)
res9: play.api.libs.json.JsResult[play.api.libs.json.JsObject] =
JsError(List((,List(ValidationError(password not confirmed,WrappedArray())))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment