我在视图(html页面)上显示错误。
该表单如下所示(为清楚起见,仅显示一个字段):
PHP Warning: Use of undefined constant section- assumed 'section' (this will throw an Error in a future version of PHP)
然后我有一个自定义javax <form action="#" th:action="@{addinvoice}" th:object="${invoicedata}" method="post">
<ul class="form-style-1">
<li>
<label>Data odbioru<span class="required">*</span></label>
<input type="date" th:field="*{receptionDate}" id="receptionDate">
<span th:if="${#fields.hasErrors('receptionDate')}" th:errors="*{receptionDate}">Error.</span>
</li>
:
Validator
由于我想100%确保验证正确,因此验证次数增加了一倍。
现在@Component
public class InvoiceFormValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return InvoiceData.class.equals(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "receptionDate", "Reception date is empty!");
InvoiceData invoicedata = (InvoiceData) target;
if (invoicedata.getReceptionDate() == null) {
errors.rejectValue("receptionDate", "Reception date cannot be empty!");
}
}
}
部分看起来像这样(为了清晰起见,其余代码已删除)
Controller
现在,当我不使用@RequestMapping(value = "/addinvoice", method = RequestMethod.POST, produces = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public String addInvoice(@CurrentUser Contractor contractor, @ModelAttribute @Validated InvoiceData invoicedata, BindingResult result, Model model, RedirectAttributes attr) {
if (result.hasErrors()) {
logger.error("BINDING RESULT ERROR: " + result.getAllErrors().toString());
logger.error("ERROR: " + result.getFieldError("receptionDate").getCode());
attr.addFlashAttribute("org.springframework.validation.BindingResult.invoicedata", result);
attr.addFlashAttribute("invoicedata", invoicedata);
model.addAttribute("invoicedata", invoicedata);
model.addAttribute("bindingResult", result);
return "add";
发送表单时,会从Logger中得到漂亮的一行:
receptionDate
因此它已正确验证。
但是我已经尝试了很多事情,但我什至无法接近证明这一点:
ERROR: Reception date is empty!
我在做什么错?我已经在Web上的几个不同页面上看到了解决方案,其构造:<span th:if="${#fields.hasErrors('receptionDate')}" th:errors="*{receptionDate}">Error.</span>
随处可见,每个人都在使用${#fields.hasErrors()}
,在我的情况下不起作用。