birdy
birdy

Reputation: 9636

How to validate multiple models in a spring mvc form?

I have a spring mvc form with multiple models. Color and Shade

I am using hibernate validator and when I only have one model the validations work perfectly. From my research I found that best way to have multiple models with spring mvc form is to create a new model that wraps both the models. So I made:

Models

public class ColorShade {

    private Color color;
    private Shade shade;

    //getter setters
}

public class Color {
  @NotEmpty
  private String name;
  //getter setters
}

public class Shade {
  @NotEmpty
  private String shadeName;
  //getter setters
}

Controller

@RequestMapping(method = RequestMethod.POST)
public String validateForm(
        @ModelAttribute("COLORSHADE") @Valid ColorShade colorShade,
        BindingResult result, Map model) {
    if (result.hasErrors()) {
        return "myForm";
    }

    return "success";
}

View

<form:form method="post" commandName="COLORSHADE" cssClass="form-horizontal" >
    <spring:bind path="COLORSHADE.color.name">
        <div class="control-group ${status.error ? 'error' : ''}">
            <label class="control-label">Color Name</label>
            <div class="controls">
                <form:input path="${status.expression}"/>
            </div>
        </div>
    </spring:bind>
    <spring:bind path="COLORSHADE.shade.shadeName">
        <div class="control-group ${status.error ? 'error' : ''}">
            <label class="control-label">Shade Name</label>
            <div class="controls">
                <form:input path="${status.expression}"/>
            </div>
        </div>
    </spring:bind>
</form>

Question

Upvotes: 2

Views: 2273

Answers (1)

Jose Luis Martin
Jose Luis Martin

Reputation: 10709

Try with:

public class ColorShade {
    @Valid
    private Color color;
    @Valid
    private Shade shade;

    //getter setters
}

See http://beanvalidation.org/1.0/spec/#d0e991

Upvotes: 2

Related Questions