In this spring mvc validation order, we will demonstrate how to use validation groups to set the order of validation. This is helpful when you want specific validation to be called first before other validators and since the default order of validators are not constant.
In order to create the validation order sequence, we must create an interface for the group, another interface for the sequence/order and in our controller we tell spring that it should use the sequence that we have defined.
For each group that you want to define, create an interface for that group.
public interface MatchGroup { }
The interface is empty without any methods. Then we add that group interface to our validators that we want to be in that group. Example, we for this User Dto:
public class UserDto { @NotExistingLoginID private String loginID; @ShouldMatchField.ShouldMatch(groups = MatchGroup.class) private String password; @ShouldMatchField.ShouldMatch(groups = MatchGroup.class) private String confirmPassword; private int role; ...getters and setters }
Here, the custom validator ShouldMatch was added in our created group interface MatchGroup. The validators such as NotExistingLoginID is not added in any group, thus, is in the Default group by default. Also read Custom Validator in Spring MVC
After defining the group interface, and setting it to our validators, now we create a new interface that will hold the validation sequence.
import javax.validation.GroupSequence; import javax.validation.groups.Default; @GroupSequence({Default.class, MatchGroup.class}) public interface ValidationSequence { }
Now that the groups and sequence has been setup, lets now add it to our spring controller methods and tell them to use this group sequence.
To use this, in the parameter of your method, instead of using @Valid annotation, we will use @Validated annotation that will contain the ValidationSequence. For example:
@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST) public String validateUser(@ModelAttribute("user_form") @Validated(ValidationSequence.class) UserDto userDto, BindingResult result) { if (result.hasErrors()) { return "user/error"; } return "user/success"; }
And that’s it, you have already created your own validation sequence.