The JSON validator is installed in the My Play application as follows:
val validateAccount = (
((__ \ 'id).json.pickBranch) ~
((__ \ 'name).json.pickBranch) ~ // mandatory
((__ \ 'mobile).json.pickBranch or emptyObj) ~ // optional
...
).reduce
The validator above accepts JSON that contains at least id and possibly a name. Is it possible to make a field required by state? For example, how to make it namemandatory when a condition is made trueand keep it optional if it is a condition false?
def validateAccount(condition: Boolean) = (
((__ \ 'id).json.pickBranch) ~
((__ \ 'name).json.pickBranch if (condition) or emptyObj else ???) ~
((__ \ 'mobile).json.pickBranch or emptyObj) ~
...
).reduce
I want emptyObjif and only if coditionthere is true- it emptyObjsimply represents an empty node:
val emptyObj = __.json.put(Json.obj())
The [bad] solution could be something like this:
def validateAccount(condition: Boolean) = {
(if (condition) {
((__ \ 'id).json.pickBranch) ~
((__ \ 'name).json.pickBranch) ~ // mandatory
((__ \ 'mobile).json.pickBranch or emptyObj) ~ // optional
...
} else {
((__ \ 'id).json.pickBranch) ~
((__ \ 'name).json.pickBranch or emptyObj) ~ // now this is optional
((__ \ 'mobile).json.pickBranch or emptyObj) ~ // optional
...
}).reduce
}
The reason I need JSON conditional validation is because when my REST api receives an insert request, JSON must be completed, and when it receives an update request, only the update field should be provided.