Update CustomConstraintValidator.java

This commit is contained in:
Pallavi Priyadarshani 2019-08-02 16:42:36 +05:30 committed by GitHub
parent d9abb296b7
commit a5f0631850
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 21 additions and 6 deletions

View File

@ -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<CustomConstraint, String> {
import com.baeldung.validation.listvalidation.model.Movie;
public class CustomConstraintValidator implements ConstraintValidator<CustomConstraint, List<Movie>> {
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if (value == null || value.isEmpty()) {
return false;
} else {
return true;
public boolean isValid(List<Movie> 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;
}
}