Error messages are not in the correct order.

In my MVC spring check, the order of my error messages changes randomly, I would like the messages to be in the same order as on the page.

My AccountForm.java class looks like this:

@NotNull(message = "Account name cannot be empty.")
@Size(min=3, max=50, message="Account name must be between 3 and 50 characters long.")
private String accountName;

@NotNull(message = "Company name cannot be empty.")
@Size(min=3, max=50, message="Company name must be between 3 and 50 characters long.")
private String companyName;

And I also add some user errors in my controller:

   public ModelAndView create(@Valid AccountForm accountForm, BindingResult bindingResult) {

    ModelAndView mav = new ModelAndView("accounts/new");
    mav.addObject("errors", bindingResult.getAllErrors());
    mav.addObject("accountForm", accountForm);

    if (!bindingResult.hasErrors()) {
        if(accountService.findByAccountName(accountForm.getAccountName()) != null) {
            bindingResult.addError(new ObjectError("accountName", "Account name is already is use"));
        }
        ..
        ..
    }

    if(bindingResult.hasErrors() {
      return mav;
    }

    ..

When I click submit on the form, the order of the posts continues to change.

I make mistakes in my view using:

        <#list errors as error>
            <li>${error.defaultMessage}</li>
        </#list>

Can this be fixed?

+5
source share
2 answers

This is achieved through validation groups, and Spring supports it. You are using the @Valid annotation , but to use groups, validations must be @Validated .

 public ModelAndView submitSearch(@Validated(value={OrderChecks.class}) @ModelAttribute("SearchStringBackingObject") final SearchStringBackingObject backingObject

OrderChecks.class:

 @GroupSequence(value={NotEmptyGroup.class, LengthCheckGroup.class, DiacriticeCheckGroup.class, EmailValidationGroup.class, EmailLengthValidationGroup.class,
    Email3EntriesValidationGroup.class, EntityAlreadyExistsValidatorGroup.class, Default.class})
 public interface OrderChecks {}

:

 @NotBlank(groups=NotEmptyGroup.class)
@Length(max=25, groups=LengthCheckGroup.class)
@DiacriticeCheck(groups=DiacriticeCheckGroup.class)
private String firstname="";

@GroupSequence .

, , , :

public interface AccountNameGroup{}

:

@GroupSequence(value={AccountNameGroup.class, the rest of groups})
public interface OrderOfGroups{}

And of course inside the Controller you specify the @Validated annotation with the OrderOFGroups interface.

,

+4

. , JSR-303.
( ) <form:error> .

0

All Articles