我无法使用thymleaf模板捕获html表单中的任何验证。
表单对象 -
public class TestForm {
....
@Pattern(regexp = "[a-zA-Z]*", message = "Only characters")
private String field1;
....
getter/setters
}
html代码 -
<div id="main">
<form action="#" th:action="@{/create}" th:object="${testForm}" method="post" >
<div>
<label> Field1:</label>
<input type="text" th:field="${testForm.field1}" name="field1" />
<div th:if="${#fields.hasErrors('field1')}" th:errors="*{field1}">errors</div>
</div>
<input type="submit" value="Submit" />
</form>
</div>
控制器 -
@RequestMapping(method= RequestMethod.POST, value = "/create")
public String createTest(@Valid @ModelAttribute("testForm") TestForm testForm, MultipartHttpServletRequest request, BindingResult bindingResult) throws IOException {
if (bindingResult.hasErrors())
return "createtestform";
不会抛出任何错误,表单会成功提交。
答案 0 :(得分:1)
我认为麻烦是因为你把BindingResult放错了。 将其替换为MultipartHttpServletRequest,它必须在之后验证参数:
@RequestMapping(method= RequestMethod.POST, value = "/create")
public String createTest(@Valid @ModelAttribute("testForm") TestForm testForm, BindingResult bindingResult, MultipartHttpServletRequest request) throws IOException {
if (bindingResult.hasErrors())
return "createtestform";
答案 1 :(得分:0)
您是否尝试删除其他操作?从此<form action="#" th:action="@{/create}" th:object="${testForm}" method="post" >
到此<form th:action="@{/create}" th:object="${testForm}" method="post" >
?
另外两个想法
也许你的javax.validation.Pattern
被某个地方覆盖了?
2.您是否尝试删除@ModelAttribute("testForm")
?因此,您的方法签名将为public String createTest(@Valid TestForm testForm, MultipartHttpServletRequest request, BindingResult bindingResult) throws IOException
。