diff --git a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/CustomConstraintValidator.java b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/CustomConstraintValidator.java index 9f18a0c218..3e80a79afe 100644 --- a/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/CustomConstraintValidator.java +++ b/spring-mvc-simple-2/src/main/java/com/baeldung/validation/listvalidation/constraint/CustomConstraintValidator.java @@ -1,17 +1,32 @@ package com.baeldung.validation.listvalidation.constraint; +import java.util.List; +import java.util.regex.Pattern; + import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; -public class CustomConstraintValidator implements ConstraintValidator { +import com.baeldung.validation.listvalidation.model.Movie; + +public class CustomConstraintValidator implements ConstraintValidator> { @Override - public boolean isValid(String value, ConstraintValidatorContext context) { - if (value == null || value.isEmpty()) { - return false; - } else { - return true; + public boolean isValid(List values, ConstraintValidatorContext context) { + boolean isValid = true; + if (values == null || values.isEmpty()) { + isValid = false; + context.disableDefaultConstraintViolation(); + context.buildConstraintViolationWithTemplate("Movie list cannot be empty.") + .addConstraintViolation(); } + String regex = "[^A-Za-z0-9].*"; + for (Movie movie : values) { + if (Pattern.matches(regex, movie.getName())) { + isValid = false; + break; + } + } + return isValid; } }