小编典典

使用thymeleaf的html表单验证无法在Spring Boot

spring-boot

我无法使用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";

不会引发任何错误,并且表单已成功提交。


阅读 530

收藏
2020-05-30

共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";
2020-05-30