1

Let's go straight to my classes 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;
...
}

and Pet.java

public class Pet {

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

and this is my form

   <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>

The code works well and shows message at form:error.. block when invalid values is entered except when it comes to petName and petAge.

Actually, the code doesn't validate petName and petAge at all. I'm using hibernate validator. Could Someone tell me How to solve this?

1 Answer 1

2

Try adding javax.validation.Valid annotation on top of 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;

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

2 Comments

See also this example
Thank you, guys. Really helpful !

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.