Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring: Same object, different validation

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

like image 606
Javi Avatar asked Mar 18 '10 09:03

Javi


1 Answers

You can use JSR-303 constraint groups to achieve this.

public class User {

    public interface GroupNewUser {};

    @NotEmpty
    private String username;

    @NotEmpty(groups = {GroupNewUser.class});
    private String password;

    // ...
}

Then in the controller, instead of using @Valid, use Spring's @Validated annotation which allows specifying a constraint group to apply.

See this blog post and this one also for more information.

There is also this superb post for Spring usage.

like image 122
bernie Avatar answered Oct 05 '22 04:10

bernie