Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to display Spring MVC form errors for class error

I'm familiar with using Spring's <form:errors> tags to display validation errors for object properties, but how do you display an error at the class level?

Here's an example of what I'm talking about:

@ScriptAssert(lang = "javascript", 
        script = "_this.isExistingEmployee == true || (_this.phoneNumber != null && _this.address != null)", 
        message = "New hires must enter contact information")
public class JobApplicationForm {

    @NotBlank(message = "First Name is required")
    private String firstName;

    @NotBlank(message = "Last Name is required")
    private String lastName;

    @NotNull(message = "Please specify whether you are an existing employee in another area")
    private Boolean isExistingEmployee;

    private String phoneNumber;

    private String address;
}

@ScriptAssert here just confirms that if the applicant has indicated that they are an existing employee they can skip the contact info, but if not they must enter it. When this validation fails, the error is not on a given field but rather is on the class.

Within the form, I can show an error on a field with <form:errors path="firstName"> and I can display all errors (class and field) at once using <form:errors path="*"> but how can I isolate and display class level errors?

like image 931
Planky Avatar asked Jul 29 '13 13:07

Planky


People also ask

Which object contains information about validation errors on your form?

Using the Validation API The validity property resolves to a ValidityState object which contains information about whether the field has validation errors, as well as the error message the browser will display to the user.

What is error tag?

The <errors> tag renders field errors in an HTML 'span' tag. Displays errors for either an object or a particular field. This tag supports three main usage patterns: Field only - set ' path ' to the field name (or path) Object errors only - omit ' path '

What is the use of BindingResult in Spring MVC?

[ BindingResult ] is Spring's object that holds the result of the validation and binding and contains errors that may have occurred. The BindingResult must come right after the model object that is validated or else Spring will fail to validate the object and throw an exception.


1 Answers

To show only class-level errors, leave the path empty.

<form:errors path="">

from the Spring docs:

  • path="*" - displays all errors
  • path="lastName" - displays all errors associated with the lastName field
  • if path is omitted - object errors only are displayed

ref: http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/view.html#view-jsp-formtaglib-errorstag

like image 88
Planky Avatar answered Sep 29 '22 18:09

Planky