java if hasvalue_java – 使用Spring通过条件验证对象字段

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 {

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> errorList = validator.validate(dependFieldValue);

for(ConstraintViolation 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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值