开发者

JSR 303 Validation Override

How can I go about overriding the validation on the email for the AuthorizedUser in the following situation:

public class Account {
    @Length(min = 1, max = 100, 
            message = "'Email' must be between 1 and 100 characters in length.")
    @NotNull(message = "'Email' must not be empty.")
    protected String email;

    @Length(min = 1, max = 50,
            message = "'Name' must be between 1 and 50 characters in length.")
    private String name;
}

public class AuthorizedUser extends Account {
    @Lengt开发者_StackOverflowh(min = 1, max = 40,
            message = "'Field' must be between 1 and 50 characters in length.")
    private String field;
}

I know I could 'hack' the solution by overriding the email address in the setter on the AuthorizedUser by doing the following:

@Override
public void setEmail(String email) {
   this.email = email;
   super.setEmail(" ");
}

It just feels dirty... Is this possible to be overridden without writing a custom validator?

I tried moving the @Valid to the setter in the super class, and leaving it off in the overridden field, but I still receive the message from the super class about it being empty. Is there a lazier way to do this?


Since constraints are aggregated through inheritance, the best solution may be to change your inheritance hierarchy to something like this:

public class BasicAccount {
  protected String email;

  @Length(min = 1, max = 50,
          message = "'Name' must be between 1 and 50 characters in length.")
  private String name;
}

public class EmailValidatedAccount extends BasicAccount {
  @Length(min = 1, max = 100, 
          message = "'Email' must be between 1 and 100 characters in length.")
  @NotNull(message = "'Email' must not be empty.")
  @Override
  public String getEmail() {
    return email;
  }
}

public class AuthorizedUser extends BasicAccount {
  @Length(min = 1, max = 40,
          message = "'Field' must be between 1 and 50 characters in length.")
  private String field;
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜