Thymeleaf form validation with spring MVC -
this has been asked few times of them did not answer question. have been trying different functionalities work thymeleaf 2 days , been unsuccessful. have been able work spring-boot, right using spring-mvc.
first show dependencies
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %> <%@ page contenttype="text/html;charset=utf-8" language="java" %> <html xmlns:th="http://www.thymeleaf.org" xmlns="http://www.w3.org/1999/xhtml"> <head> <title>create new account</title> <link th:href="@{/resources/css/loginform.css}" href="/resources/css/loginform.css" rel="stylesheet" type="text/css"/> </head> <body> <form action="#" th:action="@{/createnewaccount}" th:object="${user}" method="post"> <table> <tr> <td>name:</td> <td><input type="text" th:field="*{username}" /></td> <td th:if="${#fields.haserrors('name')}" th:errors="*{username}">name error</td> </tr> <tr> <td>password:</td> <td><input type="text" th:field="*{password}" /></td> <td th:if="${#fields.haserrors('age')}" th:errors="*{password}">password error</td> </tr> <tr> <td><button type="submit">submit</button></td> </tr> </table> </form> </body> </html>
now can see errors intellij ide showing:
user.java
package com.practice.domain; import javax.validation.constraints.notnull; import javax.validation.constraints.size; /** * created drewjocham on 8/30/15. */ public class user { @notnull @size(min = 2, max = 30) private string username; @notnull private string password; public string getusername() { return username; } public void setusername(string username) { this.username = username; } public string getpassword() { return password; } public void setpassword(string password) { this.password = password; } @override public string tostring() { return "user{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}'; } }
the field name call haserrors
needs match field name in object. so:
<td th:if="${#fields.haserrors('username')}" th:errors="*{username}">name error</td>
note haserrors('name')
became haserrors('username')
, and:
<td th:if="${#fields.haserrors('password')}" th:errors="*{password}">password error</td>
note haserrors('age')
became haserrors('password')
.
as errors being highlighted in intellij, think they're misleading, , related open issue: https://youtrack.jetbrains.com/issue/idea-132738
Comments
Post a Comment