Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 509
Aprendiendo Siempre Avatar asked Nov 15 '25 22:11

Aprendiendo Siempre


1 Answers

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.

like image 117
Nikolas Charalambidis Avatar answered Nov 18 '25 13:11

Nikolas Charalambidis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!