2

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

  • The above setup works but the validations are not working now. how can I get validations to work?
  • If I just have single model and remove the wrap around ColorShade model then the validations work perfectly fine. How can I get both, multiple models in single form and validations, to work properly?

1 Answer 1

2

Try with:

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

    //getter setters
}

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.