views:

60

answers:

2

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

+2  A: 

This is the problem with declarative validation, it's not very easy to do this sort of thing.

The easiest solution is to remove the validation annotations from the password field, and validate that field manually in the controller. The BindingResult class has methods on it for you to explicitly mark fields as invalid.

Another alternative would be to create two subclasses of the form class, each with its own password field, one with validation annotations, and one without, and use the appropriate one in the appropriate place.

skaffman
A: 

A few pointers. I'm not sure they will be useful, though:

Spring docs say that:

you may call binder.setValidator(Validator) within a @Controller's @InitBinder callback. This allows you to configure a Validator instance per @Controller class

javax.validation has two *Context interfaces. Get into more details with them to see whether different validation can be achieved in different contexts.

Bozho