How would I specify a Hibernate “@Pattern” annotation using a regular expression from a .properties file or database

前端 未结 1 493
南笙
南笙 2021-02-15 12:40

Situation: I would like to perform Hibernate Validation based upon user properties (to allow different validation rules for input based upon a user\'s account d

相关标签:
1条回答
  • 2021-02-15 13:05

    Within annotations you can only refer to constant expressions, so loading values from a property file or database wouldn't work here.

    You could use the API for dynamic constraint declaration introduced in Hibernate Validator 4.2 which allows to define constraints at runtime. Your example might look like that:

    String dynamicPattern = ...;
    
    ConstraintMapping mapping = new ConstraintMapping();
    mapping.type( ContactInfo.class )
        .property( "workPhone", FIELD )
        .constraint( new PatternDef().regexp( dynamicPattern ) );
    
    HibernateValidatorConfiguration config = 
        Validation.byProvider( HibernateValidator.class ).configure();
    config.addMapping( mapping );
    
    Validator validator = config.buildValidatorFactory().getValidator();
    
    0 讨论(0)
提交回复
热议问题