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
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;
                        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;
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With