I try to implements custom validator, in Spring boot 3 and java 17, to validate string date, but I type mismatch issue for
@Constraint(validatedBy = ...)
This is my code:
DateValidation.java
@Target( {ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = DateValidator.class)
public @interface DateValidation {
public String message() default "Invalid color: must be RED, GREEN or BLUE";
public Class<?>[] groups() default {};
public Class<? extends Payload>[] payload() default {};
}
DateValidator.java
public class DateValidator implements ConstraintValidator<DateValidation, String>
{
@Override
public boolean isValid(String stringDate, ConstraintValidatorContext cxt) {
.....
}
}
In the pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
The error on @Constraint(validatedBy)
is :
Type mismatch: cannot convert from Class<DateValidator> to Class<? extends ConstraintValidator<?,?>>[]
This generally comes from the fact that there is a javax.validation
dependency lingering in your dependencies. Spring Boot 3 supports the JakartaEE API and not the JavaEE API (as that isn't being developed any further and moved to JakartaEE).
Make sure that you are only adding the spring-boot-starter-validation
dependency. That includes all needed dependencies (both the API as well as the implementation in the form of hibernate-validator
).
Check your own pom.xml
if there are no javax.validation
dependencies lingering around. If they aren't in your own dependencies they might be pulled in by other, incompatible dependencies. Getting those can be figured out using mvn dependency:tree
.
Finally make sure you are only using the jakarta.validation
packages in your code and not mixing both javax.validation
and jakarta.validation
.