Christian Vielma
Christian Vielma

Reputation: 16035

How to display <form:errors> outside <form:form> in Spring?

I'm new to Spring and I've been having some trouble trying to show a form errors.

I have the following form:

<form:form action="loginform.html" commandName="loginForm" onsubmit="goWait();">
<table><tr>
           <td>User Name: </td>
           <td><form:input path="userName" /></td>
        </tr>
        <tr> 
           <td>Password: </td>
           <td><form:password path="password"/> </td>
        <tr>
            <td colspan="2">
             <input type="submit" value="Login" style="butt-login">
            </td>
        </tr>
</table>                                                        
</form:form>

The form, as can be seen, is backed by a LoginForm Bean that validates it.

I want to show all the errors from the validation, outside this form. Something like this:

<div>
   <ul>
      <li><form:errors path="userName"/></li>
      <li><form:errors path="password"/></li>
   </ul>
</div>

This div should be outside the , so I can't use the tag.

How can I do this?

Upvotes: 2

Views: 7025

Answers (3)

Zeeshan Cornelius
Zeeshan Cornelius

Reputation: 328

Yes, you can user form:errors tag outside form:form tag

<form:errors path="yourBindedObject.*" />
<form:form action="loginform.html" commandName="loginForm" onsubmit="goWait();">
<table><tr>
           <td>User Name: </td>
           <td><form:input path="userName" /></td>
        </tr>
        <tr> 
           <td>Password: </td>
           <td><form:password path="password"/> </td>
        <tr>
            <td colspan="2">
             <input type="submit" value="Login" style="butt-login">
            </td>
        </tr>
</table>                                                        
</form:form>

Upvotes: 4

yglodt
yglodt

Reputation: 14551

You could just capture the html produced by form:errors and display it somewhere after the form:

<form:form ...>
    <c:set var="err">
        <form:errors path="*" element="div" id="err" cssClass="hidden" />
    </c:set>
</form:form>

....

<c:out value="${err}" />

If you want to show the errors before the form, you can do that with a bit of jQuery

Upvotes: 4

Rubens Mariuzzo
Rubens Mariuzzo

Reputation: 29261

If you want to show all errors associated with any fields just pass a star to the path attribute.

<form:errors path="*" />

But if you want to show global error messages just pass an empty string:

<form:errors path="" />

More information related: http://www.mkyong.com/spring-mvc/spring-mvc-form-errors-tag-example/

Upvotes: 0

Related Questions