Search code examples
springspring-mvchibernate-validatormodelattribute

how do i validate the referenced object of another object (DTO) in Spring MVC


my UserDto class is here:

package com.carpoint.dto;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;

import com.carpoint.validation.annotation.PasswordMatches;

@PasswordMatches
public class UserDto{

    @NotEmpty
    private String username;

    @NotEmpty @Size(min=6, max=30)
    private String password;

    @NotEmpty
    private String confirmPassword;

    @NotEmpty
    private String firstname;
    @NotEmpty
    private String lastname;
    @NotEmpty @Email
    private String email;

    private UserAddressDto userAddress;

    //getters & setters
}

and UserAddressDto class here:

package com.carpoint.dto;

import org.hibernate.validator.constraints.NotEmpty;

public class UserAddressDto {

    @NotEmpty
    private String address;
    @NotEmpty
    private String country;
    @NotEmpty
    private String city;
    @NotEmpty
    private Integer pincode;

        //getters & setters
    }

My question is that the validation on UserDto is working successfully but it's not on referenced type of UserAddressDto and I want to validate UserDto's referenced type is there any way?


and here is my UserController code snippet:

 @RequestMapping(value = "/add", method = RequestMethod.POST)
        public String addUsers(@Valid @ModelAttribute("userDto")UserDto userDto, 
ModelMap model, SessionStatus status, RedirectAttributes attributes) 
throws IOException {
    ....
    ....
    }

Solution

  • Did you try putting @Valid upon private UserAddressDto userAddress; in class UserDto? I guess that should be enough as spring handles it on its own.