Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatic Bean Validation (JSR 303) without Annotation [duplicate]

Possible Duplicate:
using Hibernate Validator without calling annotation.

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

@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 Entity Classes.

But now I need to check a single String in a Service method, where I need to apply the same constraint to a single String. Because of the fact that the constraint is the same, I want to use the same definition of the constraint (@PasswordComplexity) (single 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 for an not annotated simple object (String). Is it at least possible, and how?

(I use Hibernate Validator as JSR 303 provider)

like image 962
Ralph Avatar asked Jun 10 '11 07:06

Ralph


People also ask

What is JSR 303 Bean Validation?

1 Overview of the JSR-303 Bean Validation API. JSR-303 standardizes validation constraint declaration and metadata for the Java platform. Using this API, you annotate domain model properties with declarative validation constraints and the runtime enforces them.

What is @email annotation in Spring Boot?

@Email annotation is part of javax. validation. constraints package. Using Just @Email annotation like below @Data.

What does @NotNull annotation Bean in Bean property?

@NotNull: a constrained CharSequence, Collection, Map, or Array is valid as long as it's not null, but it can be empty.


1 Answers

One way to do this would be write a full custom validator, and push the logic down into that class having the annotation just use the validator. This would mean you then had an independent compilation unit (A full class PasswordComplexityValidator implements implements ConstraintValidator<PasswordComplexity, String> ...) which you could use independently of the annotation. This approach would also make it easier for you to unit test the validation.

However, since you are using the annotation as a way of configuring the existing regex validator provided by Hibernate, you could use that one instead, passing it the constant pattern from the annotation class. You should also be able to package your length constrain into the regex too, which would be simpler and faster than having both annotations anyway.

like image 69
Simon Elliston Ball Avatar answered Oct 15 '22 18:10

Simon Elliston Ball