如何用OR条件验证2字段?

时间:2015-03-25 07:48:00

标签: java spring bean-validation jsr

我希望以一个字段有效或另一个字段有效的方式验证请求类的两个字段。

例如: 请求Bean

public class CarRequest  {
    @NotEmpty
    private String customerName;
    @NotEmpty
    private String customerId;

控制器方法

    public @ResponseBody CarResponse addCar(
            @ModelAttribute @Valid CarRequest request, BindingResult results)
            throws RuntimeException, ValidationException {
        if (results.hasErrors()) {
            LOG.error("error occured while adding the car");
            throw new ValidationException(
                    "Error Occoured while validiating car request");
        }
}

这里我要检查customerName应该是NotEmpty还是customerId应该是NotEmpty。然后我的验证应该通过。我该如何实现它。请建议!!

1 个答案:

答案 0 :(得分:7)

您需要创建自定义验证程序以验证多个字段。

创建自定义注释:

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.validation.Constraint;
import javax.validation.Payload;

@Documented
@Constraint(validatedBy = CarRequestValidator.class)
@Target({ ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestAnnotation {
    String message() default "{RequestAnnotation}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

创建自定义验证程序:

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class CarRequestValidator implements 
                ConstraintValidator<RequestAnnotation, CarRequest> {

    @Override
    public void initialize(RequestAnnotation constraintAnnotation) {

    }

    @Override
    public boolean isValid(CarRequest value, ConstraintValidatorContext context) {
        // validation logic goes here
        return false;
    }
}

现在,使用自定义注释注释您的模型:

@RequestAnnotation 
public class CarRequest  {
    private String customerName;
    private String customerId;
}