I have two seperate Models AccountDetailsForm
and AccountDetails
, former for form submission and latter for persistence.
AccountDetailsForm:
public class AccountDetailsForm {
private AccountDetails accountDetails;
@NotNull
private String confirmPassword;
//setter and getters
}
and AccountDetails:
@Entity
@Table(name = "ACCOUNT")
public class AccountDetails {
@Id
@Column(name = "USER_NAME")
@NotEmpty
@Max(value = 60)
private String userName;
@Column(name = "PASSWORD")
@NotEmpty
@Min(value = 8)
private String password;
//setters and getters
}
Now I am validating the submitted form using @Valid
:
@RequestMapping(value="userRegistration", method = RequestMethod.POST)
public ModelAndView registerUser(@Valid AccountDetailsForm accountDetailsForm, BindingResult result,Model model){
//I autowire localValidatorFactoryBean to validate the fields in AccountDetails bean.
localValidatorFactoryBean.validate(accountDetailsForm.getAccountDetails(), result);
if (result.hasErrors()){
model.addAttribute("accountDetailsForm", new AccountDetailsForm());
model.addAllAttributes(result.getModel());
return new ModelAndView("userRegistration");
}
I am using hibernate for persistence.
Is there a way to validate the accountDetails bean using @Valid
rather than explicitly calling validate()
method or using spring validator implementation?
I don't mind hearing suggestions for a confirmPassword
workaround. I am following the current approach because it doesn't make sense to have a confirmPassoword
field in the model.