gpt4 book ai didi

java - SpringMVC验证: Set specific error message for each validation check

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

我在 Spring 中使用 JSR-303 来验证密码字段。我想将所有验证逻辑放在一个类中,并相应地显示每个错误的消息。这可能吗?为每个验证检查创建一个单独的类(即PasswordLengthValidator、PasswordRegexValidator)是否是更好的做法?

目前,我只能根据密码界面显示 1 条错误消息。

这是我的 @Password 注释界面:

@Documented
@Constraint(validatedBy = PasswordValidator.class)
@Target( { ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Password {

String message() default "{Password}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};

}

这是我的 validator 类:

public class PasswordValidator implements ConstraintValidator<Password, String> {

public void initialize(Password arg0) {
// TODO Auto-generated method stub

}

public boolean isValid(String field, ConstraintValidatorContext ctx) {
// TODO validation validation validation
if(StringUtils.isEmpty(field)) {
// Message: password can not be empty
return false;
}

// match some password regex
if(field.matches("^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$")) {
// Message: password should be bla bla
return false;
}

return true;
}

}

最佳答案

您的 validator 可以发送带有 ConstraintValidatorContext 的验证消息API:

context.buildConstraintViolationWithTemplate( "this detail is wrong" )
.addConstraintViolation();

// [..]

context.buildConstraintViolationWithTemplate( "that detail is wrong" )
.addPropertyNode( "street" )
.addConstraintViolation();

关于java - SpringMVC验证: Set specific error message for each validation check,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21151969/

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