The problem with doing bean validation on a Java Boolean
I recently had to scratch my about applying Java bean validation to an optional Boolean field on JSON request body. It turns out there isn’t an easy way to check that the field is either absent, “true” or “false”. Before you can apply javax.validations
the string message must be converted to the object you expect. That is why it’s called bean validation. Validation is applied to the bean, not to the request body.
The problem is that any value assigned to “myBooleanValue” in the message is passed through Boolean.valueOf()
which will return false
for anything other than “true” or “TRUE”.
You also can’t apply validations like @Pattern(regexp = "^(true|false)$")
because those only apply to String
and can’t be applied to a Boolean
. At best you can validate @NotNull
if the field is not optional.
All of this means that you can’t prevent API consumers from sending you garbage input for “myBooleanValue” when you have logic that assigns meaning to it being null, true or false.