views:

258

answers:

1

I have a Spring 2.5 application and I have several forms where I perform various validation. I have no problem doing this validation and displaying the errors on the page next to the appropriate form input. I was wondering if I could instead put the error message in the form value so it displays in the input field instead of just in the <form:errors path="*" cssClass="error" > tag. I tried setting the value in the validator class and I see it set in the log when setting the form session attribute, but the value doesn't show on the page in the field.

For example, I have a page with a control defined like:

<form:input path="username" cssClass="textinput" cssErrorClass="textinput-error" />

In the validator, I tried to set the username value to the object:

ValidationUtils.rejectIfEmptyOrWhitespace(errors, "username", "error.field-required");
// This value doesn't show on the page
user.setUsername("You must supply a user name");

Is it possible to set the value based on an error and have it populated on the page?

A: 

Do as follows

Inside your validate method

import static org.springframework.validation.BindingResult.MODEL_KEY_PREFIX;

public void validate(Object command, Errors errors) {
    /**
      * keep in mind I SUPPOSE your model Attribute is called command - override if needed
      */
    User user = (User) ((BindingResult) errors).getModel().get(MODEL_KEY_PREFIX + "command");

    user.setUserName("You must supply a user name");

    /**
      * Now just do it
      */
    ((BindingResult) errors).getModel().put(MODEL_KEY_PREFIX + "command", user);
}

It will fullfil your needs

Warning: As message error is a plain String, you can not set up some property whose class is not a plain String

Arthur Ronald F D Garcia