I have a model object which has entities annotated with hibernate validation annotations. For example @NotBlank, @NotNull, @Length.
I have a form backing this model which decorates an instance of the model object. I have annotated this instance with an @NotNull, @Valid annotation. I am registering a validator for this backing form in the Controller Class and the form validator is being invoked when the @RequestMapping method argument is annotated with @Valid annotation.
Note the model is also annotated with the @Entity annotation, the model backing form is just
a thin wrapper around the model.
However the validations on the decorated object are not being checked? I know this because in the request mapping method definition I check the BindResult for errors and there are none.
My form fields are all empty, hence the validations on the fields on the decorated model annotated with @NotBlank should be checked. However that does not happen.
Can you help me fix this?
Edit:
Sample Code
@Entity
class MyModel {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(nullable=false)
private Long id;
@NotBlank
@Column(unique=true, length=30, nullable=false)
private String number;
@Column(length=30, nullable=false)
@Length(min=1, max=30)
private String firstName;
/* ... getters and setters ... */
}
public class MyModelBackingForm {
@NotNull
@Valid
private MyModel model;
/* ... delegate getters and setters for all fields in MyModel ... */
}
Edit:
Add Controller Code
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new MyBackingFormValidator());
}
Edit:
public class MyBackingFormValidator implements Validator {
public MyBackingFormValidator() {
super();
}
@Override
public boolean supports(Class<?> clazz) {
return Arrays.asList(MyBackingForm.class, MyModel.class).contains(clazz);
}
@Override
public void validate(Object obj, Errors errors) {
// custom validation code commented ... as I want to check if JSR 303 validations invoked
}
}
Here is a sample code the way I was using the hibernate validation. I was calling @valid on the fetched objects with the binding result. This way it knows the validations which are required to be done on the form.
Edited: How to invoke custom and standard validator?
Using @InitBinder we can pass the custom validator instance to which again we can pass the class parameter for the standard validator using binder.getValidator()
Courtesy: Rohit Banga
//Edited: