gpt4 book ai didi

java - 使用 Spring 按条件验证对象字段

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:51:59 24 4
gpt4 key购买 nike

我有一个复杂的对象,其中包含两个 UserPropertyForm 对象:

    public class ComplexUserForm {
int userType;

@Valid
UserPropertyForm property1;
UserPropertyForm property2;
...
}

public class UserPropertyForm {
@NotEmpty
@Length(max = 255)
private String title;
@NotEmpty
@Length(min = 100)
private String description;
...
}

我每次都需要验证property1,所以我将它标记为@Valid
仅当 userType == 2

时,我才需要验证 property2

谁能说我是否可以使用对 UserPropertyForm 字段的注释以一种简单的方式验证 property2

感谢您的帮助。

最佳答案

You can use this custom annotation above your class.

@ValidateIfAnotherFieldHasValue(
fieldName = "userType",
fieldValue = "2",
dependFieldName = "property2")
public class ComplexUserForm {
int userType;

@Valid
UserPropertyForm property1;
UserPropertyForm property2;

它只会在 getUserType().equals("2") 时验证 property2。

错误消息将放在 property2.fieldname 中,因此您需要 <form:errors path="property2.*"/>如果您想从 property2 中捕获所有错误,请在您的 JSP 中。

public class ValidateIfAnotherFieldHasValueValidator
implements ConstraintValidator<ValidateIfAnotherFieldHasValue, Object> {

private String fieldName;
private String expectedFieldValue;
private String dependFieldName;

@Override
public void initialize(final ValidateIfAnotherFieldHasValue annotation) {
fieldName = annotation.fieldName();
expectedFieldValue = annotation.fieldValue();
dependFieldName = annotation.dependFieldName();
}

@Override
public boolean isValid(final Object value, final ConstraintValidatorContext ctx) {

if (value == null) {
return true;
}

try {
final String fieldValue = BeanUtils.getProperty(value, fieldName);
final Object dependFieldValue = PropertyUtils.getProperty(value, dependFieldName);

if (expectedFieldValue.equals(fieldValue)) {

ctx.disableDefaultConstraintViolation();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();

Set<ConstraintViolation<Object>> errorList = validator.validate(dependFieldValue);

for(ConstraintViolation<Object> error : errorList) {

ctx.buildConstraintViolationWithTemplate(error.getMessageTemplate())
.addNode(dependFieldName+"."+error.getPropertyPath())
.addConstraintViolation();
}

return errorList.isEmpty();
}

} catch (final NoSuchMethodException ex) {
throw new RuntimeException(ex);

} catch (final InvocationTargetException ex) {
throw new RuntimeException(ex);

} catch (final IllegalAccessException ex) {
throw new RuntimeException(ex);
}

return true;
}

}

和:

@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = ValidateIfAnotherFieldHasValueValidator.class)
@Documented
public @interface ValidateIfAnotherFieldHasValue {

String fieldName();
String fieldValue();
String dependFieldName();

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

@Target({ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@interface List {
ValidateIfAnotherFieldHasValue[] value();
}

}

关于java - 使用 Spring 按条件验证对象字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13366251/

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