Programmatic Bean Check (JSR 303) without annotation

Possible duplicate:
Using the Hibernate Validator without invoking the annotation.

I have an annotation for composite constraint (for illustration only):

@Target... @Retention... @Constraint(validatedBy = {}) @Pattern(regexp = PasswordComplexity.AT_LEAST_TWO_NONE_ALPAH_CHARS) @Length(min = 6, max = 20) public @interface PasswordComplexity { ... } 

And I use it in Spring controllers and object classes.

But now I need to check one String in the service method, where I need to apply the same restriction to one String. Because the constraint is the same, I want to use the same constraint definition (@PasswordComplexity) (the only source of truth). Something like:

 public void createUser(UserDto userDto, String password) { if(hasViolation(validator.validate(password,PasswordComplexity.class))) { throw new PasswordComplexityViolationException(); } else { โ€ฆ } } 

But I do not know how to run the JSR 303 Validator on a non-annotated simple object (String). Is this possible, and how?

(I use Hibernate Validator as a JSR 303 provider)

+8
java spring hibernate bean-validation
source share
1 answer

One way to do this is to write a complete custom validator and output the logic to this class, in the annotation just use the validator. That would mean that you then had an independent compilation unit (the full PasswordComplexityValidator implements implements ConstraintValidator<PasswordComplexity, String> ... class) that you could use regardless of the annotation. This approach will also make it easier for you to test the unit test.

However, since you use annotation as a way to customize the existing regex validator provided by Hibernate, you can use it instead by passing it a constant pattern from the annotation class. You should also be able to pack the length constraint into a regular expression, which will be simpler and faster than annotation in any case.

+2
source share

All Articles