繁体   English   中英

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

[英]How can a Spring Boot web app validate a form field that is required conditional on another field?

I have a Spring Boot web app in which fields of my form-backing bean are annotated with Bean Validation annotations (see Baeldung's tutorial or the 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并且当且仅当Country等于"US"时,我希望ZipCode@NotBlank ,否则为可选。

在我的 Controller 中,使用@Valid注释非常优雅地触发了验证,并且错误附加到BindingResult object。 像这样:

@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字段。 理想情况下,我根本不必更改 Controller 代码。

您可以获得创建自定义验证器 class 的帮助,以下链接可以帮助您: https://www.baeldung.com/spring-mvc-custom-validator#custom-validation

对于这种东西,您需要使用跨字段验证。 请试试:

创建注释:

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())));
    }
}

注释您的 class:

@CustomerValid
public class Customer {
// body
}

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM