12

Is it possible to use the Hibernate validator API storing the validated object in a field with an annotation? For example, I would like to validate Email address by calling a Java method instead of putting an @Email annotation on a Java bean property.

Lii
  • 11,553
  • 8
  • 64
  • 88
EeE
  • 665
  • 5
  • 12
  • 27

2 Answers2

13

Yes, it is possible. Try Something like,

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

Car car = new Car(null);

Set<ConstraintViolation<Car>> constraintViolations =
    validator.validateProperty(car, "manufacturer");

Take a look at here.

Gama11
  • 31,714
  • 9
  • 78
  • 100
zinan.yumak
  • 1,590
  • 10
  • 9
4

zinan.yumaks solution where they are creating a dummy Car object that you don't need is not the right way to do this. There is a better solution, the validateValue method:

Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

String emailAddress = "...";

Set<ConstraintViolation<User>> constraintViolations = 
    validator.validateValue(User.class, "email", emailAddress);

From the documentation:

Validates all constraints placed on the property named propertyName of the class beanType would the property value be value.

Lii
  • 11,553
  • 8
  • 64
  • 88
  • 1
    Re: "creating a dummy Car object that you don't need" - the example that you show though is using an instance of Car. The OP is (and I am!) trying to achieve this without an object at all.. eg is string "xyz@yahoo.com" a valid email address? – Roy Truelove Mar 14 '17 at 02:16
  • @RoyTruelove: Hm, I seem to have been confused in some way when I wrote this, and now I can't remember the details. Thanks for pointing it out. It looks like `validateValue` is the right way to do this, but that the last argument should be the value being validated, ex `manufacturer` or `emailAddress`. I'll update the answer to that effect (although I haven't tested it). – Lii Mar 14 '17 at 09:06