Announcement Announcement Module
Collapse
No announcement yet.
Validation Error Messages Page Title Module
Move Remove Collapse
X
Conversation Detail Module
Collapse
  • Filter
  • Time
  • Show
Clear All
new posts

  • Validation Error Messages

    Hi,

    I currently have a scenario where I need to display all error messages at the start of the page with their respective field names, and then the error messages next to the field. To illustrate this the page may appear as:

    Sorry cannot proceed. Please correct the following errors:
    First Name: Field is required
    Surname: Field is required

    ....

    First Name: <input box> Field is required
    Surname: <input box> Field is required

    I currently have no problem displaying the error messages next to the field using JSTL to display messages from the resource bundle. I have been using a wild card to display the error messages at the start of the page, but I cannot work out how to add the field name to the start of the message.

    Any ideas on how this can be done without resorting to separate error messages such as "First Name: Field is required" for each field that is required would be appreciated.

    Thanks,

    Chris

  • #2
    Try using spring-form tld file introduced in Spring 2.0 here.

    http://www.springframework.org/docs/...-form.tld.html

    Comment


    • #3
      Weird, I just faced the exact same problem. To krishnan.1000: Sometimes it is not possible to use the new forms tag library although it would be nice (e.g. there is no form tag for file uploads). Nevertheless, back to cmelgar's problem. You can use the methods of the Errors interface. An example:

      <spring:hasBindErrors name="yourFormObject">
      <!-- all your global errors here -->
      <c:forEach items="${errors.globalErrors}" var="error">
      <spring:message code="${error.code}" /><br/>
      </c:forEach>
      <!-- all your field errors here -->
      <c:forEach items="${errors.fieldErrors}" var="error">
      <!-- you can also use error.code instead of error (which calls just FieldError#toString() -->
      <div class="error"><spring:message code="${error.field}" />: <spring:message code="${error}" /></div><br/>
      </c:forEach>
      </fieldset>
      </spring:hasBindErrors>

      Hope that helps,

      Daniel
      Last edited by dmitter; Feb 2nd, 2007, 02:10 AM. Reason: Editing error

      Comment


      • #4
        Thanks Daniel - I will give this a go.

        Comment


        • #5
          If I want to display the error message associated with the error, how would I do it? The error object can take the message from the errorcode, Object [] error Args[] or the default message. How do I just display the error message that has been associated with it, whether it is from error code, or errorArgs[] or defaultMessage. I have a lot of fields. I dont want to do spring:bind on every field

          Comment


          • #6
            Hi krishnan.1000,

            In my code, I use Errors#getCode() to display the error message. My JSP code looks as follows:
            Code:
            <spring:hasBindErrors name="myBoundObject">
              <c:forEach items="${errors.globalErrors}" var="error">
                <spring:message code="${error.code}" /><br/>
              </c:forEach>
              <c:forEach items="${errors.fieldErrors}" var="error">
                <spring:message code="${error.field}" />: <spring:message code="${error.code}" /><br/>
              </c:forEach>
            </spring:hasBindErrors>
            The text of the error message is resolved by the ResourceBundleMessageSource. The rough control flow is as follows:
            • The controller class calls the validator (which happens in BaseCommandController#bindAndValidate)
            • The validator validates the command object. An example in my case: errors.rejectValue("earliestNotificationDate", "error.outsideAllowedRange");
            • Afterwards the JSP gets rendered. The ResourceBundleMessageSource is used by the Errors object in order to resolve the message code (again, in my case: "error.outsideAllowedRange"). This text is then rendered on the resulting JSP page.

            Although I have not actually tried it I see no reason why you cannot use this code in conjunction with the new form tag library approach. Therefore you do not have to use spring:bind on each of your fields:
            Code:
            <form:form yourFormTagAttributesHere>
              <spring:hasBindErrors name="myBoundObject">
                <c:forEach items="${errors.globalErrors}" var="error">
                  <spring:message code="${error.code}" /><br/>
                </c:forEach>
                <c:forEach items="${errors.fieldErrors}" var="error">
                  <spring:message code="${error.field}" />: <spring:message code="${error.code}" /><br/>
                </c:forEach>
              </spring:hasBindErrors>
            
              <!-- just use the new tags -->
              <form:input path="property1"/><br/>
              <!-- and so on... -->
            </form:form>
            Bye,

            Daniel

            Comment


            • #7
              Hi Daniel,

              That is not the problem. In the validator, you can reject a field using ValidationUtils.reject() . The error message that is to be displayed can be taken from error code or the Object [] args or the defaultMessage.

              I wanted to know if there is a way to display the error message that is mapped to the field.

              Comment


              • #8
                Hi krishnan.1000,

                Sorry for the misunderstanding. I hope I get you right now. I think you *could* use the following snippet (untested):

                <spring:message code="${errors.fieldError('yourProperty').code}" />

                Note that only the first error message associated with this field will be displayed. Furthermore, that is an untypical approach to display error messages in Spring MVC. Using the form tag library you can just use <form:errors path="yourProperty" /> in order to display the error message for a field. Note that you can use the <form:errors/> tag only within the <form:form/> tag as the commandObject's name has to be specified (see also the reference documentation for the <forms:error/> tag). Alternatively, you can also use the traditional spring:bind tag which is more verbose:
                Code:
                <spring:bind path="yourProperty">
                  <input ...>
                  <c:out value="${status.errorMessage}" />
                </spring:bind>
                If you have properly configured your ResourceBundleMessageSource the error message will get displayed right. That's how my application_name-servlet.xml looks like:

                Code:
                <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
                  <property name="basename" value="messages" />
                  <property name="useCodeAsDefaultMessage" value="true" />
                </bean>
                Put a file "messages.properties" into your /WEB-INF/classes folder. This file contains the mappings from the error codes to the messages. e.g.:

                error.invalid.coordinate=Invalid coordinate

                If your validator rejects some field using this error code (error.invalid.coordinate) the error message "Invalid coordinate" will be displayed for the rejected field.

                Bye,

                Daniel

                Comment


                • #9
                  Hi Daniel,

                  Let me try that.

                  Thanks so much!!

                  Comment


                  • #10
                    Is there a way to get to the errors without being inside of a spring:form and being bound a specific command object?

                    I'd prefer to have a more global approach to the error messages.

                    Such that...

                    Code:
                    [        header       ]
                    [    error messages   ]
                    [nav][      body      ]
                    [       footer        ]
                    Where the spring form is almost always going to be in the body. Id like to put my error message handler in my page template (im using OpenSymphony's Sitemesh) and not have to worry about displaying errors on every page that I write.

                    Any way I can accomplish this?

                    Thanks, developers & Spring community.

                    Comment


                    • #11
                      Hi Mike,

                      A quick and dirty test of your approach worked for me. However, as you mentioned I spot a problem concerning the command object's name in the general case too. You face a problem for e.g. <spring:hasBindErrors name="myCommandObject"> for arbitrary command objects. You could circumvent this problem for example by convention (use always "command" as the command object's name) or by additional programming (you could add the command object's name e.g. in #referenceData() of your controller) However, neither approach is perfect.

                      Bye,

                      Daniel

                      Comment


                      • #12
                        Hi Daniel,

                        I found out the solution through trial and error.

                        For field errors:

                        Code:
                        <c:forEach items ="${errors.fieldErrors}" var = "err">	
                        	   			
                        	   			<spring:bind path = command.${err.field}">
                        	   				<br><c:out value = "${status.errorMessage}"/>
                        	   			</spring:bind> 
                        	   		</c:forEach>
                        Thanks to Spring Community for help

                        Comment


                        • #13
                          Code:
                          <c:forEach items ="${errors.fieldErrors}" var = "err">	
                             <spring:bind path ="command.${err.field}">
                          	<c:out value = "${status.errorMessage}"/>
                                  <br>
                             </spring:bind> 
                          </c:forEach>
                          Didn't work for me. It didn't work when I used "command" or when I used a specific command name, such as <spring:bind path ="login.${err.field}">

                          Anyone else have any luck?

                          Comment


                          • #14
                            I've got different issue:
                            I reject a value in validator with
                            ValidationUtils.rejectIfEmptyOrWhitespace(errors, "price", "validation.field.requred");

                            And i would like the error code to be just "validation.field.requred",
                            but i get "validation.field.required.item.price"

                            There should be easy solution for this I think

                            UPD: I display error on JSP with <form:errors path="price" cssClass="fieldError"/> inside <form:form commandName="item">
                            Last edited by dhr_padla; Feb 27th, 2007, 08:51 AM. Reason: missed a string

                            Comment

                            Working...
                            X