繁体   English   中英

email 的模式元注释中使用的正则表达式不起作用但在其他地方起作用

[英]Regexp used in pattern meta-annotation for email does not work but works somewhere else

我想通过 Spring 的 bean 验证使用正则表达式验证电子邮件列表。 email 的有效列表如下:

  • 某人@mail.xxx, someother@mail.xxx, anotherone@mail.xxx
  • 某人@mail.xxx, someother@mail.xxx, anotherone@mail.xxx,
  • 某人@mail.xxx,某人@mail.xxx,
    另一个@mail.xxx

无效列表可能如下所示:

  • 某个@mail.xxx 某个@mail.xxx,另一个@mail.xxx
  • , 某人@mail.xxx 某人@mail.xxx, 另一个@mail.xxx

有效 email 的用户名是除空格和换行符之外的字符序列。 这同样适用于域名和域后缀。

此外,实际 email 与其前后逗号之间的空格或换行数无关紧要,但实际电子邮件中不能有空格或换行。

我遵循其他非常有用的答案的建议来提供自定义验证器,我有这个:

@Email(message = "Please provide a list of valid email addressess")
@Pattern(regexp = "((( |\\n| \\n))*[^ \\n]+@[^ \\n]+\\.[^ \\n]+(( |\\n| \\n))*,*(( |\\n| \\n))*)+", flags = Flag.CASE_INSENSITIVE, message = "Please provide a list of valid email addresses")
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(value = RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {})
@Documented
public @interface ExtendedEmailListValidator {
    String message() default "Please provide a list of valid email addresses";

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

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

但是,所有 email 列表都不匹配,除非列表只有一个元素。

试图至少证明一些带有模式/匹配器集的基本列表,如下所示:

String input = "";
Matcher m = null;
Pattern p = Pattern.compile("((( |\\n| \\n))*[^ \\n]+@[^ \\n]+\\.[^ \\n]+(( |\\n| \\n))*,*(( |\\n| \\n))*)+");

input = "someone@mail.xxx";
m = p.matcher(input);
System.out.println(input + ": " + m.matches());

input = "someone@mail.xxx, anotherone@mail.xxx";
m = p.matcher(input);
System.out.println(input + ": " + m.matches());

input = "someone@mail.xxx,anotherone@mail.xxx";
m = p.matcher(input);
System.out.println(input + ": " + m.matches());

input = "someone@mail.xxx, an other one@mail.xxx";
m = p.matcher(input);
System.out.println(input + ": " + m.matches());

input = "someone@ma      il.xxx, anotherone@mail.xxx";
m = p.matcher(input);
System.out.println(input + ": " + m.matches());

并且 output 符合预期:

someone@mail.xxx: true
someone@mail.xxx, anotherone@mail.xxx: true
someone@mail.xxx,anotherone@mail.xxx: true
someone@mail.xxx, an other one@mail.xxx: false
someone@ma      il.xxx, anotherone@mail.xxx: false

为了使自定义验证器正常工作,我做错了什么或缺少什么? 提前致谢!

当正则表达式变得复杂时(通常是这样),将它组织成这样可能会很好。 使用 Java 使其更容易处理。

    String email = "([A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64})";
    String comma = "\\s*,\\s*";
    String optionalComma = "\\s*,?\\s*";

    Pattern p = Pattern.compile("\\s*" + email + "(" + comma + email + ")*" + optionalComma);

这在测试用例中有效。 您将需要在注释中展开正则表达式。

我错过了@Email 注释,它仅在您只需要验证一个 email 时才有用。

呸!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM