Hello,
I have an object called User where I save all the data of the User. I have some annotations to perform validation and it works fine.
public class User{
@NotEmpty
@Email
@Size(max=100)
@Column(name="username", length=100, nullable=false, unique=true)
private String username;
@NotEmpty
@Size(min=5, max=40)
@Column(name="password", length=40, nullable=false)
private String password;
@Size(min=5, max=40)
@Transient
private String newPassword;
// other attributes ,getters and setters
}
I have two different forms (each one in a different page). In the first one I ask for username and password to create the user, so both of them are compulsory.
In the second form I show the information about the user: username, other data (which will be validated as well) andthe password and newPassword. If the newPassword is set and the password is the same as the user has I'll change the user's password, but if they are left empty it means I shouldn't change the password.
The problem is that I have two forms relating to the same object where there is a different validation for the field password. In the first one it must be not empty, but in the second one it can be empty.
In the controller I validate the object in this way:
public String getUserDetails(@Valid @ModelAttribute("User") User user, BindingResult result, Model model){
if(result.hasErrors()){
//There have been errors
}
...
}
but is password is empty there will be an error.
Is there any way to perform a validation only in some fields of the object?
Can I, at least, remove any validation error after the validation?
What is the best practice in this case?
Thanks