How to validate type 'java.lang.Boolean' in Spring boot

Nobita picture Nobita · May 30, 2019 · Viewed 25.7k times · Source

I have a boolean field which I want to validate to have only "true" or "false" as value(without quotes). But this field is also allowing "true" or "false" as value(with quotes) which I want to restrict.

I tried to use @Pattern annotation to match these values. But I have the following error:

javax.validation.UnexpectedTypeException: HV000030: No validator could be found for constraint 'javax.validation.constraints.Pattern' validating type 'java.lang.Boolean'. Check configuration for 'restartable'

My code is:

@Pattern(regexp = "^(true|false)$", message = "restartable field allowed input: true or false")
private Boolean restartable;

What should i do? Is there some other way to overcome this issue? Thanks in advance.

Answer

Technoshaft picture Technoshaft · May 30, 2019

you can use @NotNull and @AssertTrue or @AssertFalse assertions present in javax.validation if the goal is to enforce non null and truthy value.

https://docs.oracle.com/javaee/7/tutorial/bean-validation001.htm

@NotNull
@AssertTrue
private Boolean restartable;

Not Null annotation would suffice if the value can be either true or false as booleans in Java can only have two values.