有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Spring Boot web应用程序如何验证另一个字段所需的表单字段?

我有一个Spring Boot web应用程序,其中表单支持bean的字段用Bean Validation注释进行注释(请参见Baeldung's tutorialthe docs at spring.io)。例如,Customer Bean上的字段可能注释如下:

@NotBlank
@Pattern(regexp="[ \\.A-Za-z-]*")
private String firstName;

@DateTimeFormat(pattern="M/d/yyyy")
@NotNull
@Past
private Date DOB;

我想知道的是:(如何)实现一个查看多个字段的复杂验证我的意思是,使用这个框架。例如,假设我有一个字段Country和一个字段ZipCode,我希望ZipCode@NotBlank当且仅当Country等于"US",否则可选

在我的控制器中,使用@Valid注释可以非常优雅地触发验证,错误会附加到BindingResult对象。就像这样:

@PostMapping("customer/{id}")
public String updateCustomer( @PathVariable("id") Integer id,
                              @Valid @ModelAttribute("form") CustomerForm form, 
                              BindingResult bindingResult ) {
    if (bindingResult.hasErrors()) {
        return "customerview";
    }
    customerService.updateCustomer(form);
    return "redirect:/customer/"+id;
}

我希望找到一种方法来编写这个条件验证器,它也会被@Valid注释触发,并将其错误消息附加到BindingResult中的ZipCode字段。理想情况下,我根本不需要更改控制器代码


共 (1) 个答案

  1. # 1 楼答案

    对于这类东西,你需要使用跨域验证。请尝试:

    创建注释:

    package foo.bar;
    
    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = {CustomerValidator.class})
    public @interface CustomerValid {
    
        String message() default "{foo.bar.CustomerValid.message}";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    
    }
    

    创建自定义验证程序:

    public class CustomerValidator implements ConstraintValidator<CustomerValid, Customer> {
    
        @Override
        public void initialize(CustomerValid constraint) {
        }
    
        @Override
        public boolean isValid(Customer customer, ConstraintValidatorContext context) {
            return !("US".equals(customer.getCountry() && "".equals(customer.getZipCode())));
        }
    }
    

    为你的班级做注解:

    @CustomerValid
    public class Customer {
    // body
    }
    

    除了现有的字段验证器之外,还将处理此类验证