html form validation using thymeleaf not working s

2020-05-08 18:58发布

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.

2条回答
smile是对你的礼貌
2楼-- · 2020-05-08 19:30

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 be public String createTest(@Valid TestForm testForm, MultipartHttpServletRequest request, BindingResult bindingResult) throws IOException.

查看更多
爷、活的狠高调
3楼-- · 2020-05-08 19:46

I think the trouble because you placed BindingResult incorrect. Replace it with MultipartHttpServletRequest, it must be after the validating parameter:

@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";
查看更多
登录 后发表回答