senderj
senderj

Reputation: 410

spring form validation in object

Say my command looks like this

public class MyForm {
    @Max(99)
    private int mode;
    private MyObj myObj;

and my MyObj is

public class MyObj {
    private String myStr;
    private int myInt;

and my controller looks like this

@Controller
public class MyController {
    @RequestMapping(value = "/Anything.htm")
    public String AnythingMethod(@Valid MyForm myForm, .....

and my JSP looks like this

<form:input path="mode"/>
<form:input path="myObj.myStr"/>

how can I inject validation such as @NotNull @MAx @Min for myStr and myInt? how can I specify their error messages in messages.properties? Please help.

Upvotes: 0

Views: 67

Answers (1)

ivan.sim
ivan.sim

Reputation: 9288

Unsure if the codes posted in your question are complete, you might be missing a few annotations. Also, since you mentioned in your comment that validations on some of the other fields work, I'm going to assume that you have all the dependencies sorted out.

So try this:

In your MyForm class:

public class MyForm {
    @Max(99, message="{myform.mode.max}")
    private int mode;

    @Valid // add @valid annotation
    private MyObj myObj;

In your MyObj class:

public class MyObj {
    @NotBlank(message="{myobj.mystr.notnull}")
    private String myStr;

    @Max(/* some value */, message="{myobj.mystr.max}")
    @Min(/* some value */, message="{myobj.mystr.min}")
    private int myInt;

In your MyController class:

@Controller
public class MyController {
    @RequestMapping(value = "/Anything.htm") /* add @ModelAttribute annotation */       
    public String AnythingMethod(@Valid @ModelAttribute('myForm') MyForm myForm, .....) 

As for specifying the error messages in a .properties file, put them all into a ValidationMessages.properties file, and add this file to the root of your classpath. (For e.g., /WEB-INF/classes, resources folder etc.).

Hope this helps.

Upvotes: 1

Related Questions