I would like to compare two fields in my entity and check if maxField is greater than minField to be valid. Below is my implementation but I cannot see the custom message, instead it returns this with 400 bad request:
{
"errors": []
}
my dto:
@ValidMaxMinDouble(
maxFieldName = "maxOperatingTemperature",
minFieldName = "minOperatingTemperature",
message =
"Maximum operating temperature must not be less than the minimum operating temperature")
@Data
public class RequestDTO {
@ValidDoubleRange(min = -100, max = 100, required = true)
private Double maxOperatingTemperature;
@ValidDoubleRange(min = -100, max = 100, required = true)
private Double minOperatingTemperature;
}
and here is my validator:
@Documented
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ValidMaxMinDoubleValidator.class)
public @interface ValidMaxMinDouble {
String message() default "The maximum value must be greater than or equal to the minimum value";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
String maxFieldName();
String minFieldName();
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@interface List {
ValidMaxMinDouble[] value();
}
}
class ValidMaxMinDoubleValidator implements ConstraintValidator<ValidMaxMinDouble, Object> {
private String maxFieldName;
private String minFieldName;
private String message;
@Override
public void initialize(ValidMaxMinDouble constraintAnnotation) {
this.maxFieldName = constraintAnnotation.maxFieldName();
this.minFieldName = constraintAnnotation.minFieldName();
this.message = constraintAnnotation.message();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
Double maxValue = (Double) new BeanWrapperImpl(value).getPropertyValue(maxFieldName);
Double minValue = (Double) new BeanWrapperImpl(value).getPropertyValue(minFieldName);
if (maxValue == null || minValue == null) {
return false;
}
boolean valid = maxValue >= minValue;
if (!valid && !message.isEmpty()) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate(message).addConstraintViolation();
}
return valid;
}
}
I cannot see whay I cannot see custom error message. The request I sent triggers context.disabledisableDefaultConstraintViolation() part.
I replicated here https://github.com/sbernardo/spring-issues-examples/tree/main/sof-questions-77724410 the case.
Dependencies pom.xml:
I also added a
@ControllerAdviceto intercept all errors and return aBadRequestwith custom messages. You can customize response structure.Let me know if miss something, hope this will help ;)