Skip to content

Instantly share code, notes, and snippets.

@mandubian
Forked from playxamplez-admin/CODE
Last active December 20, 2015 03:49
Show Gist options
  • Save mandubian/6066416 to your computer and use it in GitHub Desktop.
Save mandubian/6066416 to your computer and use it in GitHub Desktop.
#json #Reads 2 fields that must be present exclusively #XOR #play2.1
import play.api.libs.json._
import play.api.libs.functional.syntax._
val r = (
(__ \ "field1").readNullable[String] and
(__ \ "field2").readNullable[Int]
).tupled.filter(ValidationError("unexpected result")){
case( Some(x), None ) => true;
case ( None, Some(x) ) => true;
case _ => false
}
scala> Json.obj("field1" -> "toto").validate(r)
res19: play.api.libs.json.JsResult[(Option[String], Option[Int])] = JsSuccess((Some(toto),None),)
scala> Json.obj("field2" -> 5).validate(r)
res20: play.api.libs.json.JsResult[(Option[String], Option[Int])] = JsSuccess((None,Some(5)),)
scala> Json.obj("field2" -> "toto").validate(r)
res21: play.api.libs.json.JsResult[(Option[String], Option[Int])] = JsError(List((/field2,List(ValidationError(validate.error.expected.jsnumber,WrappedArray())))))
scala> Json.obj("field1" -> "toto", "field2" -> 5).validate(r)
res22: play.api.libs.json.JsResult[(Option[String], Option[Int])] = JsError(List((,List(ValidationError(unexpected result,WrappedArray())))))
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment