Getting checkboxes to work correctly with Spring Form validation

I had a problem recently handling checkboxes within the Spring form validation framework. The checkbox would fail to retain its on state when the form was submitted and the validation failed. The checkbox was tied to a boolean attribute in the form object, so I’d followed the standard method of binding a field to the form in the JSP, as shown below.

<spring:bind path="myForm.booleanFieldName"> <input type="checkbox" name="<c:out value="${status.expression}"/>" value="true" <c:if test="${status.value}">checked</c:if>> </spring:bind>

But this didn’t work. It turns out you need to include an additional hidden field due to the nature of checkboxes – when a checkbox is not checked, the checkbox name is not present in the request parameters. Spring does support checkbox handling. You just need a hidden field with the same name as the checkbox but with a leading underscore, as shown below.

<spring:bind path="myForm.booleanFieldName">
<input type="hidden" name="_<c:out value="${status.expression}"/>" value="visible" />
<input type="checkbox" name="<c:out value="${status.expression}"/>" value="true" <c:if test="${status.value}">checked</c:if>>
</spring:bind>

3 Responses

  1. Nice tip. It helped me.

    Thank you.

  2. Thanks for this post!

  3. In addition to what is mentioned by Tim above, if we use , it will automatically create the hidden field having the _ prefix.

Leave a Reply