Rezan Achmad
Rezan Achmad

Reputation: 1920

How to override existing Hibernate Validator?

I would like to override the built-in validator of @Email.

Reason: The built-in validator implements deprecated RFC 2822. I want to create custom validator that implements RFC 5322.

I know how to create custom constrain annotation e.g. @EmailRFC5322 with its validator, but I want to use existing @Email annotation with custom validator.

Upvotes: 1

Views: 332

Answers (1)

mark_o
mark_o

Reputation: 2533

Custom validators for existing constraints can be provided either programmatically:

HibernateValidatorConfiguration configuration = Validation
    .byProvider( HibernateValidator.class )
    .configure();

ConstraintMapping constraintMapping = configuration.createConstraintMapping();

constraintMapping
    .constraintDefinition( Email.class )
    .includeExistingValidators( false )
    .validatedBy( MyEmailValidator.class );

configuration.addMapping( constraintMapping );

Or it can also be done through xml:

<constraint-definition annotation="org.hibernate.validator.constraints.URL">
  <validated-by include-existing-validators="false">
     <value>org.hibernate.validator.constraintvalidators.RegexpURLValidator</value>
  </validated-by>
</constraint-definition>

See this part of the documentation for more details

Upvotes: 2

Related Questions