I have a User Modal
public class RegisterUser {
@Size(min = 2, max = 30)
private String fname;
@Size(min = 2, max = 30)
private String lnam
I don't know if this is possible with Bean Validation, but you can set up different implementations of Spring's Validation Interface for different request parameters.
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String submitRegisterForm(@Valid RegisterUser registerUser, ...
and
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String submitMyprofileForm(@Valid RegisterUser registerUserProfile, ...
And then you can use @InitBinder
to connect different Validators to your request params. You would add these methods to your controller. Just omit the validation you dont want in the second Validator.
@InitBinder("registerUser")
protected void initUserBinder(WebDataBinder binder) {
binder.setValidator(new RegisterUserValidator());
}
@InitBinder("registerUserProfile")
protected void initUserBinderProfile(WebDataBinder binder) {
binder.setValidator(new RegisterUserProfileValidator());
}
Then you would need to do the annotation stuff manually. You could also use inheritance for your Validators, because they are exactly the same, except the one additional field validation for registration forms.
public class RegisterUserValidator implements Validator {
public boolean supports(Class clazz) {
return RegisterUser.class.equals(clazz);
}
public void validate(Object obj, Errors e) {
ValidationUtils.rejectIfEmpty(e, "publicProfile", "empty");
RegisterUser r = (RegisterUser) obj;
if (r.getFname().length() < 2) {
e.rejectValue("fname", "min");
} else if (r.getFname().length() > 30) {
e.rejectValue("fname", "max");
}
// ...
}
}
You can use Validation Groups (for different scenarios) and Spring's @Validated annotation to specify which group you want to use