Search code examples
javaspringhibernatevalidationannotations

How can I validate a collection of string and each element as a URL?


I want to validate URLs in a Collection<String>. Each element is a URL that I get as a string in the form.

@Valid
@URL
@ElementCollection 
public Collection<String> getPictures() {       
    return this.pictures;   
}

public void setPictures(final Collection<String> pictures) {         
      this.pictures = pictures;     
}

I want to know if there is some annotation in Spring that allows me to validate all the strings in this collection like URLs


Solution

  • There is no annotation that validates the field directly. The idea of a custom annotation @URL is perfectly valid, yet you have to implement the validation itself - the annotation is just a mark that "something should happen with this".

    I suggest you rename @URL to @URLCollection to avoid conflict with the class java.net.URL. Start with defining the annotation. Don't forget to the annotation @Constraint (look at its documentation to learn how to define the custom validation annotation properly):

    @Target({ElementType.METHOD, ElementType.FIELD})
    @Retention(RetentionPolicy.RUNTIME)
    @Constraint(validatedBy = UrlCollectionValidator.class)     // will be created below
    public @interface URLCollection {
        String message() default "default error message";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    }
    

    Then continue with the implementation of ConstraintValidator:

    public class UrlCollectionValidator implements ConstraintValidator<URLCollection, Collection<String>> {
    
        @Override
        public void initialize(URLCollectionconstraint) { }
    
        @Override
        public boolean isValid(Collection<String> urls, ConstraintValidatorContext context) {
            return // the validation logics
        }
    }
    

    Well, that's all. Read more about this at Configuring Custom Constraints at the Spring documentation:

    Each bean validation constraint consists of two parts: * A @Constraint annotation that declares the constraint and its configurable properties. * An implementation of the javax.validation.ConstraintValidator interface that implements the constraint’s behavior.