为什么我的内部对象自定义验证程序不用于验证?

时间:2019-04-25 12:40:54

标签: java spring spring-boot validation thymeleaf

我有一个自定义验证器,如下所示:

@Component
public class PersonFormValidator implements Validator {

    Logger logger = LoggerFactory.getLogger(com.myapp.generator.component.impl.PersonFormValidator.class);

    @Override
    public boolean supports(Class<?> clazz) {
        return Contractor.class.equals(clazz);
    }

    @Override
    public void validate(Object target, Errors errors) {
        Contractor contractor = (Contractor) target;
        if (contractor.getContractorData().getNip() == null || contractor.getContractorData().getNip().equals("")) {
            errors.rejectValue("contractorData.nip", "empty");
        }
        logger.error(errors.toString());
    }
}

在Thymeleaf模板一侧,看起来像这样:

<form action="#" th:action="@{/contractor/update/{id}(id=${contractor.id})}" th:object="${contractor}" method="post">
        <ul class="form-style-1">
<li>
     <label>NIP<span class="required">*</span></label>
     <input type="text" th:field="*{contractorData.nip}" id="nip" th:value="${contractor.contractorData?.nip}" >
     <span class="error" th:if="${#fields.hasErrors('contractorData.nip')}" th:errors="*{contractorData.nip}">Generic error</span>
</li>

我的控制器如下:

@RequestMapping(value = "/contractor/update/{id}", method = RequestMethod.POST, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String updateContractor(@PathVariable("id") String id, @Validated @ModelAttribute("contractor") Contractor contractor, Model model, BindingResult result) {
if (result.hasErrors()) {
    logger.error("BINDING RESULT ERROR");
    return "index";
} else {
    Contractor contractorPO = contractorRepository.findById(id).get();
    ContractorData contractorData = 
    //not important code here
    contractorPO.setContractorData(contractorData);
    contractorRepository.save(contractorPO);
    model.addAttribute("contractor", contractorPO);
    return "index";
}

当然我已经注册了验证者:

@InitBinder({"invoicedata", "contractor"})
protected void initPersonFormBinder(WebDataBinder binder) {
    binder.addValidators(invoiceFormValidator, personFormValidator);
}

启动应用程序并转到应用程序地址时,出现如下错误:

  

验证器的无效目标   [com.myapp.generator.component.impl.InvoiceFormValidator@e52be6c]:   承包商(id = 5cc193e581c7dc75cfb7bcff,email=some@mail.com,   contractorData = ContractorData(firstName =名称,lastName =姓氏,   businessName = Apple,businessLocation =华沙,nip =,   regon = adgadgdagdag),发票= [])

什么都没有为我工作,自昨天以来我一直在与这个问题作斗争...

我可以在代码中进行哪些更改以使验证有效?

1 个答案:

答案 0 :(得分:1)

我的猜测是两种验证器都适用于两种形式:

  • 对于invoiceData;申请invoiceFormValidator和personFormValidator
  • 对于承包商;申请invoiceFormValidator和personFormValidator

如果将验证器绑定到两个单独的方法中怎么办?

@InitBinder("invoicedata")
protected void invoiceDataBinder(WebDataBinder binder) {
    binder.setValidator(invoiceFormValidator);
}

@InitBinder("contractor")
protected void contractorDataBinder(WebDataBinder binder) {
    binder.setValidator(personFormValidator);
}