From a5f06318502750a5593578761cdbd7f3176554a3 Mon Sep 17 00:00:00 2001 From: Pallavi Priyadarshani <50460471+pallavi-priyadarshani@users.noreply.github.com> Date: Fri, 2 Aug 2019 16:42:36 +0530 Subject: [PATCH] Update CustomConstraintValidator.java --- .../constraint/CustomConstraintValidator.java | 27 ++++++++++++++----- 1 file changed, 21 insertions(+), 6 deletions(-) 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; } }