本文介绍了使用 thymeleaf 的 html 表单验证不工作 Spring Boot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用 thymleaf 模板捕获 html 表单中的任何验证.

表单对象 -

公共类TestForm {....@Pattern(regexp = "[a-zA-Z]*", message = "仅字符")私人字符串字段1;....吸气剂/二传手}

html 代码 -

<form action="#" th:action="@{/create}" th:object="${testForm}" method="post" ><div><标签>字段 1:</label><input type="text" th:field="${testForm.field1}" name="field1"/><div th:if="${#fields.hasErrors('field1')}" th:errors="*{field1}">errors</div>

<input type="submit" value="Submit"/></表单>

控制器 -

@RequestMapping(method= RequestMethod.POST, value = "/create")public String createTest(@Valid @ModelAttribute("testForm") TestForm testForm, MultipartHttpServletRequest request, BindingResult bindingResult) 抛出 IOException {如果 (bindingResult.hasErrors())返回创建测试表单";

没有报错,表单提交成功.

解决方案

我觉得麻烦是因为你放置的 BindingResult 不正确.用MultipartHttpServletRequest替换它,它必须在验证参数之后:

@RequestMapping(method= RequestMethod.POST, value = "/create")public String createTest(@Valid @ModelAttribute("testForm") TestForm testForm, BindingResult bindingResult, MultipartHttpServletRequest request) 抛出 IOException {如果 (bindingResult.hasErrors())返回创建测试表单";

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.

解决方案

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";

这篇关于使用 thymeleaf 的 html 表单验证不工作 Spring Boot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 23:44