Search code examples
javabean-validationhibernate-validator

custom bean validation in java


i have been looking for a way to validate a bean for only certain properties instead of all the properties.

For Ex:

public Class TestA {

 @NotEmpty
 private String first;

 @NotEmpty
 @Size(min=3,max=80)
 private String second;

 //getters and setters

}

i have another class called 'TestB' which is referreing to Class 'TestA' as below

public Class TestB {

 @NotEmpty
 private String other;

 @Valid
 private TestA testA; 

 //public getters and setters
}

is it possible to write a custom annotation validator to validate only certain properties? something like below...

public Class TestB {

 @NotEmpty
 private String other;

 @CustomValid(properties={"second"})
 private TestA testA; 

 //public getters and setters
}

Solution

  • Use groups attribute to do that. It will looks like this:

    public Class TestA {
    
     @NotEmpty(groups = {Second.class})
     private String first;
    
     @NotEmpty(groups = {Second.class})
     @Size(min=3,max=80, groups = {Second.class})
     private String second;
    
     //getters and setters
    
    }
    

    and

    public Class TestB {
    
     @NotEmpty
     private String other;
    
     @Valid
     private TestA testA; 
    
     //public getters and setters
    }
    

    Where Second is an empty interface which defined somewhere.

    For more details see examples in documentation: 2.3. Validating groups Also, if you use Spring >= 3.1 you may be interesting in @Validates annotation which allows to enable validation of specified groups.