开发者

JSF Validator ordering

I am having a problem with some bean validation.

Basically I have a form where internet users can create a new profile, and they must input their username there.

I want to validate the username with regards to:

  1. Length
  2. Pattern
  3. If the username already exists

For bullet 3 I wrote my own custom validator @UserExists. The problem is that I do not want to have this validator run if any of the first two validators fail.

I have found that using the @GroupSequence on my UserExists validator does the trick with regard to the sequence, but JSF will still call my validator if one of the other validators reports that the input is invalid. Can I somehow ch开发者_如何学Goeck if one of the other validators failed already?

Here is the property I wanted to have checked:

@Size(min = 3, max = 20)
@Pattern(regexp = "[A-Za-z]+[A-Za-z0-9]*")
@UserExists(message = "User already exists")
private String username;

The custom validator has the following attributes:

@Target({ElementType.METHOD, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = UserExistsValidator.class)
@GroupSequence({Size.class, Pattern.class})
public @interface UserExists


The @GroupSequence annotation is intended to be specified on the bean hosting the constraints. As members validation groups must be specified, not single constraints.

So your example might be implemented like that:

@GroupSequence({Form.class, ExpensiveChecks.class})
public class Form {

    public interface ExpensiveChecks {}

    @Size(min = 3, max = 20)
    @Pattern(regexp = "[A-Za-z]+[A-Za-z0-9]*")
    @UserExists(message = "User already exists", groups=ExpensiveChecks.class)
    private String username;

}

That way the default group sequence for the Form type is redefined. At first the @Size and @Pattern constraints are validated. Only if that succeeds the @UserExists constraint (which is part of the ExpensiveChecks group) will be validated.

You can learn more about group sequences and the redefinition of default group sequences in the Hibernate Validator reference guide and the Bean Validation specification.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜