3

I am creating Spring boot APIs and one of the API consumening data below:

class DataRequest{

    @Size(min=1, max=10)
    private String dataTitle;

    private List<String> emails;

}

How can we validate List like all strings must be valid emails or matching with some pattern by utilizing a validation framework in Spring controller using @Valid annotation?

Nitin
  • 2,701
  • 2
  • 30
  • 60
  • 1
    I don't think it is possible to do that directly. Is it an option to have a `List` and using `@Size` in the `Email` bean? – Ishan Aug 28 '23 at 06:49

2 Answers2

3

Bean validation allows you to put the validating annotation inside the container type such as List. They refer this as the container element constraint validation.

So you can do something likes :

class DataRequest{

    @Size(min=1, max=10)
    private String dataTitle;

    private List<@Email String> emails;

}

or

class DataRequest{

    @Size(min=1, max=10)
    private String dataTitle;

    private List<@Pattern(regexp = "[A-Za-z\\d]*") String> emails;

}
Ken Chan
  • 84,777
  • 26
  • 143
  • 172
0

In fact ,if you want to control the size of list ,you may use the @Size on you parameter, some @valid annotation has support List.
But if you want to make some complicated function, i suggest you implement your own validation annotation by the support of @Valid.
Follow i will show you a simple implement:

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import java.util.HashSet;
import java.util.Set;

import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * @author yujin
 */
@Documented
@Constraint(validatedBy = {Show.ShowConstraintValidator.class})
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RUNTIME)
public @interface Show {
    String message() default "{com.annotation.Show.message}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    int[] value();

    class ShowConstraintValidator implements ConstraintValidator<Show, Integer> {

        private Set<Integer> set = new HashSet<>();

        @Override
        public void initialize(Show constraintAnnotation) {
            int[] value = constraintAnnotation.value();
            for (int i : value) {
                set.add(i);
            }
        }



        @Override
        public boolean isValid(Integer value, ConstraintValidatorContext context) {
            return set.contains(value);
        }
    }
}

The dependency is :

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
ash
  • 26
  • 3