Spring-mvc – Spring MVC with Hibernate Validator. How to validate property by group

bean-validationhibernate-validatorspring-mvc

There are two problems:

1.Sping/MVC use hibernate validater, Custom validater how to show message?
like: Cross field validation with Hibernate Validator (JSR 303)

@FieldMatch.List({
    @FieldMatch(fieldName="password",verifyName="passwordVerify",message="password confirm valid!", groups={Default.class})
})
@ScriptAssert(lang="javascript",script="_this.name.equals(_this.verifyCode)")
public class LoginForm {...}

How to show the message in jsp with resource property file?

NotEmpty.loginForm.name="username can not be empty!"
NotEmpty.loginForm.password="password can not be empty!"

2. I want to use group validater with spring mvc, like one userform for login and register

    @FieldMatch.List({
    @FieldMatch(fieldName="password",verifyName="passwordVerify",message="password confirm valid!", groups={Default.class})
})@ScriptAssert(lang="javascript",script="_this.name.equals(_this.verifyCode)",groups={Default.class,LoginChecks.class,RegisterChecks.class})
public class LoginForm {
    @NotEmpty(groups={Default.class,LoginChecks.class,RegisterChecks.class})
    @Size(min=3,max=10,groups={LoginChecks.class,RegisterChecks.class})
    private String name;

    @NotEmpty(groups={Default.class,LoginChecks.class,RegisterChecks.class})
    @Size(max=16,min=5,groups={LoginChecks.class,RegisterChecks.class})
    private String password;

    private String passwordVerify;

    @Email(groups={Default.class,LoginChecks.class,RegisterChecks.class})
    private String email;

    private String emailVerify;
...
}

Controller parameter annotation is @valid, any annotation support group validater by group?

First post 🙂

Best Answer

Update:

Spring 3.1 provides the @Validated annotation which you can use as a drop-in replacement for @Valid, and it accepts groups. If you are using Spring 3.0.x You can still use the code in this answer.

Original Answer:

This is definitely a problem. Since the @Valid annotation doesn't support groups, you'll have to perform the validation yourself. Here is the method we wrote to perform the validation and map the errors to the correct path in the BindingResult. It'll be a good day when we get an @Valid annotation that accepts groups.

 /**
 * Test validity of an object against some number of validation groups, or
 * Default if no groups are specified.
 *
 * @param result Errors object for holding validation errors for use in
 *            Spring form taglib. Any violations encountered will be added
 *            to this errors object.
 * @param o Object to be validated
 * @param classes Validation groups to be used in validation
 * @return true if the object is valid, false otherwise.
 */
private boolean isValid( Errors result, Object o, Class<?>... classes )
{
    if ( classes == null || classes.length == 0 || classes[0] == null )
    {
        classes = new Class<?>[] { Default.class };
    }
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    Set<ConstraintViolation<Object>> violations = validator.validate( o, classes );
    for ( ConstraintViolation<Object> v : violations )
    {
        Path path = v.getPropertyPath();
        String propertyName = "";
        if ( path != null )
        {
            for ( Node n : path )
            {
                propertyName += n.getName() + ".";
            }
            propertyName = propertyName.substring( 0, propertyName.length()-1 );
        }
        String constraintName = v.getConstraintDescriptor().getAnnotation().annotationType().getSimpleName();
        if ( propertyName == null || "".equals(  propertyName  ))
        {
            result.reject( constraintName, v.getMessage());
        }
        else
        {
            result.rejectValue( propertyName, constraintName, v.getMessage() );
        }
    }
    return violations.size() == 0;
}

I copied this source from my blog entry regarding our solution. http://digitaljoel.nerd-herders.com/2010/12/28/spring-mvc-and-jsr-303-validation-groups/

Related Topic