Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom class level bean validation constraint

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.

like image 654
AnkeyNigam Avatar asked Oct 31 '22 18:10

AnkeyNigam


1 Answers

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
    }
}
like image 121
Jan B. Avatar answered Nov 16 '22 09:11

Jan B.