user614868
user614868

Reputation:

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
}

Upvotes: 0

Views: 1375

Answers (1)

Slava Semushin
Slava Semushin

Reputation: 15214

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.

Upvotes: 1

Related Questions