gpt4 book ai didi

java - 使用@Validated验证序列和短路

转载 作者:太空宇宙 更新时间:2023-11-04 15:05:26 24 4
gpt4 key购买 nike

我有以下需要验证的 bean:

@FieldMatch.List({ @FieldMatch(first = "newPassword", second = "confirmNewPassword", groups=CheckFieldMatchPasswordValidationGroup.class) })
public class ChangePasswordFormModel implements BaseModel<UserEntity>{
@NotEmpty(groups=CheckEmptyPasswordValidationGroup.class)
@Length(min = 6, max = 20, groups=CheckLengthPasswordValidationGroup.class)
private String oldPassword;
@NotEmpty(groups=CheckEmptyPasswordValidationGroup.class)
@Length(min = 6, max = 20, groups=CheckLengthPasswordValidationGroup.class)
private String newPassword;
@NotEmpty(groups=CheckEmptyPasswordValidationGroup.class)
@Length(min = 6, max = 20, groups=CheckLengthPasswordValidationGroup.class)
private String confirmNewPassword;

...
}

首先,我想验证具有标记 CheckEmptyPasswordValidationGroup.class 的约束。如果发现错误,验证将停止,然后返回到表单。如果没有错误,将继续进行下一个验证组。

我在 Controller 中使用 @Validated 标记,如下所示:

public ModelAndView changePassword(
@ModelAttribute("changePasswordForm") @Validated(
{ CheckEmptyPasswordValidationGroup.class,
CheckLengthPasswordValidationGroup.class,
CheckFieldMatchPasswordValidationGroup.class }) final ChangePasswordFormModel cpfm,
final BindingResult result, RedirectAttributes redirectAttributes) throws Exception {

final boolean formHasErrors = result.hasErrors();
// do something here....
}

我的问题是,在上面的实现中,所有验证组都被执行并显示所有错误。我想保留使用 @Validated 而不是 calling each validator 。是否可以缩短验证而不必分解我的验证步骤?

最佳答案

我认为这样的事情不可能开箱即用。这个实用方法怎么样?

public boolean isValid(ChangePasswordFormModel cpfm, Class<?> ... groups) {
for(Class<?> c : groups) {
if(validator.validate(cpfm, c).size() > 0) {
return false
}
}
return true;
}

关于java - 使用@Validated验证序列和短路,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22060972/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com