Reputation: 1261
It's pretty straightforward to validate all the fields in a object by binding the object to a form and using the @Valid
notation for the object in the validating controller method.
Let's say I have an update screen that only allows the user to update some of the fields. Is there away to avoid having manual validation?
Thanks!
Upvotes: 1
Views: 420
Reputation: 5274
To have a validation against a subset of validation rules, you can use the spring feature of validation groups with @Validated
You will have to define a set of groups for your bean or form model similar to this
public class Form {
public interface Group1 { /*empty interface*/ };
public interface Group2 { /*empty interface*/ };
@NotEmpty(groups = { Group1.class }) // associate constraints
private String field1; // to a validation group
@NotEmpty(groups = { Group2.class })
private String field2;
}
And in your controller, you can use the annotation like this
@Controller
public class FormController {
@RequestMapping(value = "/validate1", method = RequestMethod.POST)
public String updateGroup1(@Validated(Form.Group1.class) Form form, Errors errors) {
if (errors.hasErrors()) {
// return to the same view
}
// return success
}
}
You can find here a good example for it
https://narmo7.wordpress.com/2014/04/26/how-to-set-up-validation-group-in-springmvc/
Upvotes: 3