Question

I have a 2 item form, that requires that both fields be entered. I'm using annotated validations, and am getting error messages, but they do not print the field name, just "may not be blank" instead of "one may not be blank" where one is the field name.

Any ideas? This is a pretty simple example:

@Controller
@SessionAttributes
 public class HomeController
{

private static final Logger logger  = LoggerFactory
                                            .getLogger(HomeController.class);

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model)
{
    logger.info("Welcome home! The client locale is {}.", locale);
    model.addAttribute("homeformitem", new HomeFormItem());
    return "home";
}

@RequestMapping(value = "/", method = RequestMethod.POST)
public String home(
        @ModelAttribute("homeformitem") @Valid HomeFormItem item,
        BindingResult result)
{
    logger.info("Posting form");
    logger.info(item.toString());
    if (result.hasErrors())
    {
        return "home";
    } else
    {
        logger.info("No Errors");
        return "done";
    }
}
}

Here is the form. I get the error message, but not the field name.

Form Validation!

    <f:form method="post" modelAttribute="homeformitem">
    <fieldset>
        <legend>Fields</legend> 
    <table>
        <tr><td colspan="3"><f:errors path="*"/></td></tr>
        <tr>
            <td><f:label path="one" for="one">One: </f:label></td>
            <td><f:input path="one" /></td>
            <td><f:errors path="one" cssClass="errorblock"/></td>
        </tr>
        <tr>
            <td><f:label path="two" for="two">Two: </f:label></td>
            <td><f:input path="two" /></td>
            <td><f:errors path="two" cssClass="errorblock"/></td>
        </tr>
        <tr>
            <td colspan="3"><input type="submit" value="Test" /></td>
        </tr>
    </table>
</fieldset>
</f:form>

Was it helpful?

Solution

You need a validation.properties file at /WEB-INF/messages with an entry similar to this (for example):

NotEmpty.homeFormItem.one=The field {0} is empty

And don't forget to add a spring bean to resolve your validation messages:

<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
    <property name="basename" value="/WEB-INF/messages/validation" />
</bean>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top