Custom class level bean validation constraint
Asked Answered
L

2

7

I already know how to add annotation based validation on specific attributes in Entity class like :-

public class Person {

    @NotNull
    private String firstName;

    private String lastName;

    //...
}

But is it possible to add annotation on class Person, in order to validate all the attributes inside this class, by creating a Customised Validation Class and handling validation there somewhere like :-

@Retention(value = RetentionPolicy.RUNTIME)      
@Target(value = ElementType.METHOD)
public @interface PersonneName {
public String firstName();
}

I am working on a project to get Constraints from Database and creating Customised Validation Class and applying on the Entity class attributes according to the constaints got from DB. Please suggest.

Linstock answered 1/10, 2015 at 6:50 Comment(1)
Possible duplicate of How can I validate two or more fields in combination?Watt
C
5

Yes, of course, it's possible. First, create the definition of your annotation. Pretty much like you did in your example, however, with a different @Target type

@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = PersonValidator.class)    
public @interface ValidPerson {
    String message () default "Your custom message";
    Class<?>[] groups () default {};
    Class<? extends Payload>[] payload () default {};
}

Then implement the validator whose isValid method takes the instance of your Person class:

 public class PersonValidator implements ConstraintValidator<ValidPerson, Person> {
  
    @Override
    public boolean isValid (Person person, ConstraintValidatorContext context) {
        // your validation logic
    }
}
Cadaverine answered 27/8, 2018 at 14:55 Comment(0)
C
1

Sure it is possible, just check the documentation regarding how to write custom class level constraints - http://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-class-level-constraints

The important thing of course is that you make sure that one can actually place the constraint annotation on the type level. For that you need to add ElementType.TYPE to the @Target annotation.

Closelipped answered 1/10, 2015 at 12:33 Comment(3)
thanks @hardy.. So will it be possible to handle validations of all the attributes of the entity Class , while annotating with the CustomValidator and handling all the validation there in CustomValidatorLinstock
You will get passed the whole instance, so you have access to all its properties and methods. It is up to you do then develop the appropriate validation logic.Closelipped
If you could provide small snippet that would help a lotLinstock

© 2022 - 2024 — McMap. All rights reserved.