Wednesday, October 7, 2009

Form Validation using Spring with Freemarker

Form validation with Spring MVC (SimpleFormController) Freemarker

Here is a simple freemarker template for a form

<html>
<body>
<#include "spring.ftl" />
<@spring.bind "command" />
<@spring.showErrors />
<form method="POST">
<@spring.bind "command.field1" />
Field <input type="text" name="${spring.status.expression}" value="${spring.status.value?default("")}"> <@spring.showErrors />
<input type="submit">
</form>

</body>
</html>

The important thing to note here is that the spring freemarker macro to show errors is mentioned twice. The reason is that errors are specific to a bind path. If a error is rejected for a field ( something like ValidatorUtils.rejectIfEmpty(...) ) then it will appear only in bind scope of the field, i.e after you have done <@spring.bind "command.field1" /> . If you have a generic error, something which you create with errors.reject(...), then this will be for the object "command" and will appear in the first <@spring.showErrors />


I hope posts like these get solved

No comments: