My email string field is annotated with javax.validation.constraints.Email
:
import javax.validation.constraints.Email;
public class MyModel {
@Email
private String email;
}
Currently hibernate-validator's org.hibernate.validator.internal.constraintvalidators.AbstractEmailValidator
automatically validates it when the corresponding api endpoint is called:
@Controller("/v1")
@Validated
public class MyController {
...
@Put(uri = "/{id}")
@Produces("application/json")
public IdType updateEntity(@Valid MyModel model) {
return delegate.updateEntity(model);
}
}
How can I register my custom class to validate the email field with Micronaut's validator, while still using the original javax.validation.constraints.Email
annotation?
This is what my custom constraint validator looks like:
import javax.inject.Singleton;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.constraints.Email;
@Singleton
public class EmailValidator implements ConstraintValidator<Email, String> {
@Override
public void initialize(Email constraintAnnotation) {}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
return value.contains("@");
}
}
Micronaut version: 1.1.4
It seems that what you are looking for is this:
HibernateValidatorConfiguration configuration = Validation
.byProvider( HibernateValidator.class )
.configure();
ConstraintMapping constraintMapping = configuration.createConstraintMapping();
constraintMapping
.constraintDefinition( Email.class )
.includeExistingValidators( false )
.validatedBy( MyEmailValidator.class );
configuration.addMapping( constraintMapping );
That's a programmatic way of "replacing" the existing validator for existing constraint. For more details on this check this part of the doc
Change your validator from @Email
to @MailAdress
or any non-standard annotation. Everyone expects @Email
as an import from Javax / Hibernate.
If you want to add a behaviour you may also check @Pattern
(as dot is not checked in @Email
annotation)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.