2016-07-28 89 views
0

我正在玩Spring validating form input示例 - java spring mvc with Thymeleaf views。我能夠毫無問題地將消息傳遞到視圖中。這些顯示了示例希望他們...在輸入標記中添加綁定錯誤消息到自定義消息

例如,

<td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td> 

我試圖找到一種方法,把它們放到HTML輸入驗證屬性,雖然,所以我曾嘗試以下(全下方頁)

<td><input type="text" th:field="*{age}" **required="required" data-errormessage-value-missing="${#fields.errors('age')}" data-errormessage="${#fields.errors('age')}"**/></td> 

這樣做沒有好,雖然與驗證消息顯示爲$ {#fields.errors('age')}!有沒有辦法將綁定錯誤推送到屬性中,還是我誤解了它的工作方式?

感謝您提前提供任何幫助。

HTML頁面

<html> 
<body> 
    <form action="#" th:action="@{/}" th:object="${personForm}" method="post"> 
     <table> 
      <tr> 
       <td>Name:</td> 
       <td><input type="text" th:field="*{name}" required="required" data-errormessage-value-missing="Custom Message" /></td> 

       <td th:if="${#fields.hasErrors('name')}" th:errors="*{name}">Name Error</td> 
      </tr> 
      <tr> 
       <td>Age:</td> 
       <td><input type="text" th:field="*{age}" required="required" data-errormessage-value-missing="${#fields.errors('age')}" data-errormessage="${#fields.errors('age')}"/></td> 
       <td th:if="${#fields.hasErrors('age')}" th:errors="*{age}">Age Error</td> 
      </tr> 
      <tr> 
       <td><button type="submit">Submit</button></td> 
      </tr> 
     </table> 
    </form> 
</body> 
</html> 

回答

0

Thymeleaf僅計算與日開始的屬性:,所以爲了做到這一點,你必須使用日:ATTR。你是標籤應該是這樣的:

<input type="text" th:field="*{age}" required="required" th:attr="data-errormessage-value-missing=${#fields.errors('age')}, data-errormessage=${#fields.errors('age')}" /> 

你也可以使用這個插件來評估數據的標籤,但我從來沒有用它之前,所以我不能以及它如何運作評論:https://github.com/mxab/thymeleaf-extras-data-attribute

+0

嗨,非常感謝。它沒有完全解決問題,但指出了我的正確方向。 th:attr屬性看起來不錯,但是我的代碼沒有選擇出錯信息。如果存在錯誤,則打印一行文本,因此必須可以查詢綁定錯誤對象,但我還沒有設法獲取特定消息!我已經停止了,現在相信你已經回答了問題的癥結所在(這個評論是爲了防止後來人們爲什麼將它標記爲答案,但實際的代碼行不起作用!)再次感謝。 – gringogordo