user19937
user19937

Reputation: 587

adding constraints dynamically to hibernate validator in a spring mvc application

I am using hibernate validator in my spring mvc app. With the following simple steps I am able to get the validation happen.

  1. pom.xml changes to add hibernate validator.
  2. Annotated the beans with some constraints.
  3. Annotated the controller method parameter with @Valid.
  4. Handled the MethodArgumentNotValidException

I don't want to add the constraints to the beans, instead want to add them to the beans dynamically. This dynamic addition need to happen during application startup and just once.

In the hibernate validator documentation, I see the following snippet.

constraintMapping.type( Car.class ).property( "manufacturer", FIELD ).constraint( new NotNullDef() )

My question is, how do I get a handle to this ConstraintMapping instance ? I see that Spring instantiates the hibernate validator through the LocalValidatorFactoryBean. thanks for your help.

Upvotes: 2

Views: 3807

Answers (1)

Hardy
Hardy

Reputation: 19109

You get it from the HibernateValidatorConfiguration - http://docs.jboss.org/hibernate/validator/5.1/reference/en-US/html_single/#section-programmatic-api

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

ConstraintMapping constraintMapping = configuration.createConstraintMapping();

constraintMapping
    .type( Car.class )
        .property( "manufacturer", FIELD )
            .constraint( new NotNullDef() )
        .property( "licensePlate", FIELD )
            .ignoreAnnotations()
            .constraint( new NotNullDef() )
            .constraint( new SizeDef().min( 2 ).max( 14 ) )
    .type( RentalCar.class )
        .property( "rentalStation", METHOD )
            .constraint( new NotNullDef() );

Validator validator = configuration.addMapping( constraintMapping )
        .buildValidatorFactory()
        .getValidator();

This mean, however, that you probably cannot use LocalValidatorFactoryBean, but you probably can just write your own.  

Upvotes: 3

Related Questions