I had a similar issue with form validation of a Boolean value, where I technically only wanted the client to pass either true or false, no other values, to ensure they understood they were actually passing those values, and not passing an integer and my code running based on the interpretted value of false (Boolean.valueOf() returns false for basically anything besides true).
To clarify the problem statement, since some people seem a little confused, boolean validation fails here because they can pass
{...
"value":8675309,
...}
where value is SUPPOSED to be boolean (but clearly passed as int), however the validator/converter just runs Boolean.valueOf() on the passed in object, which in this case would result in false, which could result in downstream logic and changes that the client was NOT expecting (ie if boolean value was something like keepInformation, that above scenario could result in a user losing all of their information because the form wasn't correctly validated, and you possibly being on the hook since the client didn't "technically" say "keepInformation":false)
Anyways, in order to combat this, I found the easiest way was to store the boolean as a String like such
@NotNull
@Pattern(regexp = "^true$|^false$", message = "allowed input: true or false")
private String booleanField;
I've tested this regex and it will ONLY pass for "value":true/"true", or "value":false/"false", it will fail on extra quotes ("value":"\"true\""), whitespace ("value":"true "), and anything else that doesn't match what I put above.
Then in your own getter in that data object you can run the boolean conversion yourself for downstream use.
public boolean isSomething() {
return Boolean.valueOf(booleanField);
}
Pattern
annotation checks aCharSequence
not aBoolean
Object according to the documentation: docs.oracle.com/javaee/7/api/javax/validation/constraints/… You would need to change your type to aString
in order to usePattern
. Alternatively you may create your own validator or check whether there is a boolean validator already – Drucie