在检查我想知道的值之前,在我自己的类级验证器中,其他验证器是否将其标记为有效?
例如,在检查数据库中是否存在该国家之前,我需要确保它通过其他测试,例如有效长度和匹配模式。
怎么做?
为了澄清我真正想要的东西,这是现实生活中的例子:
@ValidCredentials(groups = AuthAccountForm.FormChecks.class)
public class AuthAccountForm {
@NotEmpty(groups = Login1Checks.class)
@Size.List({
@Size(min = LOGIN_MIN_LENGTH, message = "{value.too-short}", groups = Login2Checks.class),
@Size(max = LOGIN_MAX_LENGTH, message = "{value.too-long}", groups = Login2Checks.class)
})
@Pattern(regexp = LOGIN_REGEXP, message = "{login.invalid}", groups = Login3Checks.class)
private String login;
@NotEmpty(groups = Password1Checks.class)
@Size(min = PASSWORD_MIN_LENGTH, message = "{value.too-short}", groups = Password2Checks.class)
@Pattern(
regexp = PASSWORD_REGEXP,
message = "{password.invalid}",
groups = Password3Checks.class
)
private String password;
@GroupSequence({ Login1Checks.class, Login2Checks.class, Login3Checks.class })
public interface LoginChecks { }
public interface Login1Checks { }
public interface Login2Checks { }
public interface Login3Checks { }
@GroupSequence({ Password1Checks.class, Password2Checks.class, Password3Checks.class })
public interface PasswordChecks { }
public interface Password1Checks { }
public interface Password2Checks { }
public interface Password3Checks { }
public interface FormChecks { }
}
在控制器中:
@RequestMapping(method = RequestMethod.POST)
public String processInput(
@Validated({
LoginChecks.class,
PasswordChecks.class,
FormChecks.class
}) final AuthAccountForm form,
final BindingResult result) {
所以,现在在ValidCredentialsValidator
检查密码和登录之前,我需要确保它们有效。
答案 0 :(得分:0)
我认为你应该使用群组和群组序列。在组序列中,如果至少一个约束失败,则序列中的以下组的约束得到验证。有关更多信息,请here。
例如:
@GroupSequence({ Person.class, Group1.class, Group2.class })
class Person {
@Size(min=4, groups=Group1.class)
@Pattern("[a-z]+", groups=Group1.class)
@CheckExistence(groups=Group2.class)
String country;
}
在此示例中,如果我们验证默认组,则首先验证属于Person的约束,然后验证Group1的约束和Group2的约束。如果Group1的一个约束令人满意,则Group2未经过验证。