带有注释的Spring MVC验证在嵌套字段中不起作用

时间:2016-03-16 10:27:36

标签: java validation spring-mvc

让我们直接进入我的班级Person.java

public class Person {

    @Size(min=4, max=10)
    private String name;

    @Range(min=0, max=80)
    private Integer age;

    @NotEmpty
    private String address;

    @Pattern(regexp="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")
    private String email;

    @Past
    private Date birth;

    private Pet pet;
...
}

和Pet.java

public class Pet {

    @NotEmpty
    public String name;
    @NotEmpty
    public Integer age;
...
}

这是我的表格

   <form:form action="enter" method="post" commandName="personForm">
name:   <form:input  path="name"/>      <form:errors path="name" />     <br/>
age:    <form:input  path="age"/>       <form:errors path="age" />      <br/>
address:<form:input  path="address"/>   <form:errors path="address" />  <br/>
email:  <form:input  path="email"/>     <form:errors path="email" />    <br/>
birth:  <form:input  path="birth"/>     <form:errors path="birth" />    <br/>
petName:<form:input  path="pet.name"/>  <form:errors path="pet.name" /> <br/>
petAge: <form:input  path="pet.age"/>   <form:errors path="pet.age" />  <br/>
<input type="submit" value="Register"/> <br/>
</form:form>

代码运行良好,并在表单中显示消息:error ..阻止输入无效值,除非涉及petName和petAge。

实际上,代码根本没有验证petName和petAge。 我正在使用hibernate验证器。有人能告诉我如何解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

尝试在javax.validation.Valid之上添加pet注释。

public class Person {

    @Size(min=4, max=10)
    private String name;

    @Range(min=0, max=80)
    private Integer age;

    @NotEmpty
    private String address;

    @Pattern(regexp="^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$")
    private String email;

    @Past
    private Date birth;

    @Valid  // This line   
    private Pet pet;

}