自定义验证器可以根据hibernate验证器中的验证失败而有多条消息吗?

时间:2014-02-28 17:43:23

标签: java spring hibernate-validator

我有一个自定义验证来检查课程中的电子邮件字段。

注释界面:

@ReportAsSingleViolation
@NotBlank
@Email
@Target({ CONSTRUCTOR, FIELD, METHOD, PARAMETER, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = CustomEmailValidator.class)
@Documented
public @interface CustomEmail {
  String message() default "Failed email validation.";

  Class<?>[] groups() default {};

  Class<? extends Payload>[] payload() default {};
}  

CustomEmailValidator类:

public class CustomEmailValidator implements ConstraintValidator<CustomEmail, String> {

  public void initialize(CustomEmail customEmail) {
    // nothing to initialize
  }

  public boolean isValid(String email, ConstraintValidatorContext arg1) {
    if (email != null) {
    String domain = "example.com";
    String[] emailParts = email.split("@");

      return (emailParts.length == 2 && emailParts[1].equals(domain));
    } else {
      return false;
    }
  }
}  

我为所有自定义消息使用 ValidationMessages.properties 文件。在属性文件中,我使用以下代码引用上述代码中的失败:

CustomEmail.email=The provided email can not be added to the account.  

问题是此错误消息用于验证期间的所有失败,因此即使用户提供了空白字符串,它也会打印该消息。我想要做的是,如果验证在@NotBlank上失败,则打印“必填字段消息”,如果它在@Email失败,则提供“无效电子邮件”消息。然后,只有当它失败时,自定义验证才会打印CustomEmail.email消息。同样在我的注释界面中,@NotBlank@Email按顺序发生,或者是否随机运行。那么首先运行的验证是否作为错误返回?我的验证要求它们按照列出的顺序运行@NotBlank,然后是@Email,然后是CustomEmail。

3 个答案:

答案 0 :(得分:0)

您可以创建一个定义预期错误类型的枚举,然后使用其值从配置中检索正确的错误消息。像

这样的东西
/**
  <P>Defines the type of email-formatting error message.</P>
 **/
public enum EmailErrorTypeIs {
  /**
     <P>...</P>

     @see  #INVALID
     @see  #OTHER
   **/
  BLANK,
  /**
     <P>...</P>

     @see  #BLANK
   **/
  INVALID,
  /**
     <P>...</P>

     @see  #BLANK
   **/
  OTHER;
};

您可以这样使用:

if(input == null  ||  input.length() == 0)  {
   throw  new IllegalArgumentException(getErrorFromConfig(EmailErrorTypeIs.BLANK));
}  else  if...

答案 1 :(得分:0)

请注意,在自定义约束中,没有定义任何顺序。即便这样你首先列出@NotBlank然后@Email,也没有订单保证。 Java本身没有在注释中定义任何顺序。如果要定义订单,则需要使用组和/或组序列。在这种情况下,您也不能使用组合约束,因为组合约束的组定义将被忽略。仅适用主要约束的组。

答案 2 :(得分:0)

关闭@ReportAsSingleViolation。每次违规都会得到ConstraintViolation,并且可以相应地工作。

关于订单,按照@ Hardy的回答。