I am unable to catch any validation in html form using thymleaf template.
Form Object -
public class TestForm {
....
@Pattern(regexp = "[a-zA-Z]*", message = "Only characters")
private String field1;
....
getter/setters
}
html code -
<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>
controller -
@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";
No error is thrown and form gets submitted successfully.
Did you try removing the other action? From this
<form action="#" th:action="@{/create}" th:object="${testForm}" method="post" >
to this<form th:action="@{/create}" th:object="${testForm}" method="post" >
?Two more ideas.
1. Maybe your
javax.validation.Pattern
got overridden somewhere?2. Have you tried removing the
@ModelAttribute("testForm")
? So your method signature will bepublic String createTest(@Valid TestForm testForm, MultipartHttpServletRequest request, BindingResult bindingResult) throws IOException
.I think the trouble because you placed BindingResult incorrect. Replace it with MultipartHttpServletRequest, it must be after the validating parameter: