Restrict String field, to not accept true/false as the field value
Any ideas, how should I restrict String field in the Request Body, to not be able to have true or false as it's value. Couldn't find anything similar here. Ideally 400 Bad request would be the best solution. I am hoping that there is something from the javax.validation
@Setter
@Getter
@ToString
public class FeeGroupBody {
@JsonProperty("ext_group_id")
@NotNull
private String groupExtId;
@JsonProperty("ext_fee_id")
@NotNull
private String feeExtId;
}
As already suggested you can do this using a custom annotation and custom validator. You would begin with the custom annotation:
@Documented
@Constraint(validatedBy = NotTrueOrFalseStringValidator.class)
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface NotTrueOrFalseString {
String message() default "String value is one of the following invalid values: true or false";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
And then the custom validator:
public class NotTrueOrFalseStringValidator implements ConstraintValidator<NotTrueOrFalseString, String> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
return !org.apache.commons.lang3.StringUtils.equalsIgnoreCase("true", value) &&
!org.apache.commons.lang3.StringUtils.equalsIgnoreCase("false", value);
}
}
Then you just need to apply it in your model:
@Setter
@Getter
@ToString
public class FeeGroupBody {
@JsonProperty("ext_group_id")
@NotNull
@NotTrueOrFalseString
private String groupExtId;
@JsonProperty("ext_fee_id")
@NotNull
@NotTrueOrFalseString
private String feeExtId;
}
You can read more about custom validators at https://www.baeldung.com/spring-mvc-custom-validator.