Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Pattern annotation on List of Strings

I am using javax.validation.constraints.Pattern.

The pojo i'm adding the pattern also contains a List object. How can I add the @Pattern annotation so it would check the elements?

@NotNull
private List<String> myListOfStrings;

Thanks

like image 492
Guy Wald Avatar asked Sep 15 '25 11:09

Guy Wald


2 Answers

See Container element constraints. With Bean Validation 2.0 you should be able to add your constraints to type arguments. In your case, you'll have:

@NotNull
private List<@Pattern(regexp="pattern-goes-here") String> myListOfStrings;
like image 180
mark_o Avatar answered Sep 18 '25 09:09

mark_o


If instead of String you had some custom object, annotating the List with @Valid and expressing the rules in the custom object would do the trick.

For this case (you cannot express validations in the String class) I believe the best chance is a custom validator to apply a pattern on a list of strings:

@NotNull
@ListPattern("regexp")
private List<String> myListOfStrings;

The annotation would roughly look like:

@Constraint(validatedBy=ListPatternValidator.class)
@Target({ METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER })
@Retention(RUNTIME)
public @interface ListPattern {
    ... // standard stuff
}

And the validator:

public class ListPatternValidator
    implements ConstraintValidator<ListPattern, List<?>> {

    public void initialize(ListPattern constraintAnnotation) {
        // see Pattern implementation
    }

    public boolean isValid(List<?> value, ConstraintValidatorContext context) {
        for( Object o : value ) {
            if( does not match ) return false;
        }
        return true;
    }
}
like image 38
Nikos Paraskevopoulos Avatar answered Sep 18 '25 08:09

Nikos Paraskevopoulos