mardi 22 octobre 2019

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

I want to validate a list of emails with a regexp thru Spring's bean validation. A valid list of email is like follows:

  • someone@mail.xxx, someother@mail.xxx, anotherone@mail.xxx
  • someone@mail.xxx, someother@mail.xxx, anotherone@mail.xxx,
  • someone@mail.xxx , someother@mail.xxx,
    anotherone@mail.xxx

An invalid list may look like:

  • some one@mail.xxx someother@mail.xxx, anotherone @mail.xxx
  • , someone@mail.xxx someother@mail.xxx, anotherone @mail.xxx

The username of a valid email is a sequence of characters other than space and new line. The same aplies for the domain name and the domain suffix.

Additionally, the number of spaces or new lines between the actual email and its preceding or following comma does not matter, but there cannot be spaces nor new lines in the actual emails.

I follow the suggestions of other really helpful answers to provide a custom validator and I have this one:

@Email(message = "Please provide a list of valid email addressess")
@Pattern(regexp = "([^ \\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 {};
}

However, all email lists do not match except the case of a list with just one element.

Tried to at least prove some basic lists with a pattern/matcher set like so:

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());

and the output is as expected:

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

What am I doing wrong or what is missing in order for the custom validator to work? Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire