@Validation 支持组概念,可以校验一组。
JSR-303’s @Valid annotation for method level validation. Moreover, we also use it to mark a member attribute for validation. However, this annotation doesn’t support group validation.
Groups help to limit the constraints applied during validation. One particular use case is UI wizards. Here, in the first step, we may have a certain sub-group of fields. In the subsequent step, there may be another group belonging to the same bean. Hence we need to apply constraints on these limited fields in each step, but @Valid doesn’t support this.
In this case, for group-level, we have to use Spring’s @Validated, which is a variant of this JSR-303’s @Valid. This is used at the method-level. And for marking member attributes, we continue to use the @Valid annotation.
@RequestMapping(value = "createAccount")
public String stepOne(@Valid Account account) {...}
public class Account {
@NotBlank
private String username;
@Email
@NotBlank
private String email;
}
而 Validation
@RequestMapping(value = "stepOne")
public String stepOne(@Validated(Account.ValidationStepOne.class) Account account) {...}
@RequestMapping(value = "stepTwo")
public String stepTwo(@Validated(Account.ValidationStepTwo.class) Account account) {...}
可以是:
public class Account {
@NotBlank(groups = {ValidationStepOne.class})
private String username;
@Email(groups = {ValidationStepOne.class})
@NotBlank(groups = {ValidationStepOne.class})
private String email;
@NotBlank(groups = {ValidationStepTwo.class})
@StrongPassword(groups = {ValidationStepTwo.class})
private String password;
@NotBlank(groups = {ValidationStepTwo.class})
private String confirmedPassword;
interface ValidationStepOne {
// validation group marker interface
}
interface ValidationStepTwo {
// validation group marker interface
}
}