private boolean validateInterestDate(Object validateThis, ConstraintValidatorContext ctx, Field fieldObj, Field dependentFieldObj) throws IllegalAccessException { InterestDate interestDate = (InterestDate) fieldObj.get(validateThis); Interest interest = (Interest) dependentFieldObj.get(validateThis); if (interest != null && !interestTypeIsNoInterest(interest.getType())) { Set<ConstraintViolation<Object>> violations = validator.validate(interestDate); if (!violations.isEmpty()) { ctx.disableDefaultConstraintViolation(); ctx.buildConstraintViolationWithTemplate(getViolationMessages(violations, ctx)) .addPropertyNode(field) .addConstraintViolation(); return false; } } return true; }
private boolean validateRate(Object validateThis, ConstraintValidatorContext ctx, Field fieldObj, Field dependentFieldObj) throws IllegalAccessException { BigDecimal rate = (BigDecimal) fieldObj.get(validateThis); Interest.InterestType type = (Interest.InterestType) dependentFieldObj.get(validateThis); if ((type == null || !interestTypeIsNoInterest(type)) && rate == null) { ctx.disableDefaultConstraintViolation(); ctx.buildConstraintViolationWithTemplate("may not be null") .addPropertyNode(field) .addConstraintViolation(); return false; } return true; }
@Override public boolean isValid(final String password, final ConstraintValidatorContext context) { final PasswordValidator validator = new PasswordValidator(singletonList( new LengthRule(8, 30) // More rules can be added to increase security )); final RuleResult result = validator.validate(new PasswordData(password)); if (result.isValid()) { return true; } context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate( validator.getMessages(result).stream().collect(joining("\n")) ).addConstraintViolation(); return false; }
@Override public boolean isValid(List<String> values, ConstraintValidatorContext context) { if(values == null || values.isEmpty()) { return true; } for (String val : values) { boolean valid = false; for(String cat: categories) { if(cat.equals(val)) { valid = true; } } if(!valid) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate(message).addConstraintViolation(); return false; } } return true; }
@Override public boolean isValid(CountyCourtJudgment ccj, ConstraintValidatorContext context) { if (ccj == null) { return true; } PaymentOption type = ccj.getPaymentOption(); boolean payByDateIsPopulated = ccj.getPayBySetDate().isPresent(); boolean repaymentPlanIsPopulated = ccj.getRepaymentPlan().isPresent(); boolean isValidImmediately = type.equals(IMMEDIATELY) && !payByDateIsPopulated && !repaymentPlanIsPopulated; boolean isValidFull = type.equals(FULL_BY_SPECIFIED_DATE) && payByDateIsPopulated && !repaymentPlanIsPopulated; boolean isValidByInstalments = type.equals(INSTALMENTS) && !payByDateIsPopulated && repaymentPlanIsPopulated; return isValidImmediately || isValidFull || isValidByInstalments; }
@Override public boolean isValid(String value, ConstraintValidatorContext context) { if(value == null) { return false; } check = new SafeguardCheck(); parametros.forEach((parametro) -> check.elementOf(value, parametro).validate()); if(check.hasError()) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate("(" + value + ") contém caracteres inválidos ") .addConstraintViolation(); } return !check.hasError(); }
@Override public boolean isValid(String value, ConstraintValidatorContext context) { if (value == null) { return true; } final boolean valid = Arrays.asList(strings).contains(value); if (!valid) { HibernateConstraintValidatorContext hibernateContext = context.unwrap(HibernateConstraintValidatorContext.class); hibernateContext.disableDefaultConstraintViolation(); hibernateContext.addExpressionVariable("validValues", Joiner.on(" ").join(strings)) .buildConstraintViolationWithTemplate(hibernateContext.getDefaultConstraintMessageTemplate()) .addConstraintViolation(); } return valid; }
@Override public boolean isValid(String value, ConstraintValidatorContext context) { // 不能9位以下纯数字 if (value.matches("^\\d{1,9}")) { return false; } // 不能相同字符组成 if (value.matches("^(.)\\1+$")) { return false; } // 不能由连续字符组成 if (consectiveStr(value)) { return false; } return true; }
@Override public boolean isValid(Object value, ConstraintValidatorContext context) { if (null == value) { return false; } Class<?>[] classes = annotation.value(); for(Class<?> cls : classes) { if (cls.isInstance(value)) { return true; } } return false; }
@Override public boolean isValid(String value, ConstraintValidatorContext context) { if (null == value) { return false; } CreditCardType[] types = annotation.value(); for(CreditCardType creditCardType : types) { CreditCardValidator ccv = new CreditCardValidator(creditCardType.getInternalValue()); if (ccv.isValid(value)) { return true; } } return false; }
@Override public boolean isValid(String value, ConstraintValidatorContext context) { if (null == value) { return false; } ParseableType type = annotation.value(); switch (type) { case TO_INT: return catcher(value, Integer::parseInt); case TO_DOUBLE: return catcher(value, Double::parseDouble); case TO_LONG: return catcher(value, Long::parseLong); case TO_SHORT: return catcher(value, Short::parseShort); case TO_FLOAT: return catcher(value, Float::parseFloat); } return false; }
@Override public boolean isValid(final String value, final ConstraintValidatorContext context) { try { if (StringUtils.isEmpty(value)) { return true; // do not validate empty value there are other constraints for that e.g. @NotNull, @Size etc... } final Path path = Paths.get(value); if (checkIfExists && !path.toFile().exists()) { return false; } final String fileExt = FilenameUtils.getExtension(value); return allowableFileExtensions.isEmpty() || !allowableFileExtensions.stream().filter(fileExt::equalsIgnoreCase).findFirst().orElse(StringUtils.EMPTY).isEmpty(); } catch (final InvalidPathException e) { LOGGER.error(e.getMessage(), e); return false; } }
@Override public boolean isValid(Object value, ConstraintValidatorContext context) { Object fieldValue = new BeanWrapperImpl(value).getPropertyValue(field); Object fieldMatchValue = new BeanWrapperImpl(value).getPropertyValue(fieldMatch); boolean result = false; if(fieldValue != null) { //Passwords are kept as char arrays, other values mostly as Strings if(fieldValue instanceof char[]) result = Arrays.equals((char[])fieldValue, (char[])fieldMatchValue); else result = fieldValue.equals(fieldMatchValue); } else result = fieldMatchValue == null; return result; }
@Override public boolean isValid(MultipartFile[] multipartFiles, ConstraintValidatorContext constraintValidatorContext) { long _totalSize = 0L; if (multipartFiles == null || multipartFiles.length <= 0) { return allowEmpty; } boolean result = false; for (MultipartFile multipartFile : multipartFiles) { result = (allowSize(multipartFile) && allowContentType(multipartFile)); if (!result) { return false; } _totalSize += multipartFile.getSize(); } /* totalSize = 0 ,则不限制 如果超出大小,则限制 */ return totalSize == 0 || _totalSize < totalSize; }
public boolean isValid(Object value, ConstraintValidatorContext context) { boolean returnValue = false; try { Comparable first = (Comparable) getNestedProperty(value, property); Object second = getNestedProperty(value, otherProperty); if (first == null) { returnValue = true; } else if (second != null) { returnValue = doComparison(first, second, comparison); } // Wenn first != null und second == null: Prüfung würde NPE bewirken, einfach false zurückgeben. } catch (Exception e) { throw new ValidationException("Cannot read property " + property + " and comparison property " + otherProperty); } if (!returnValue) { createViolationMessageForNestedProperty(property, messageTemplate, context); } return returnValue; }
static void createViolationMessageForNestedProperty(final String nestedProperty, final String messageTemplate, final ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); String[] splitted = nestedProperty.split("\\."); ConstraintValidatorContext.ConstraintViolationBuilder builder = context.buildConstraintViolationWithTemplate(messageTemplate); ConstraintValidatorContext.ConstraintViolationBuilder.NodeBuilderDefinedContext nodeDefinedContext = null; ConstraintValidatorContext.ConstraintViolationBuilder.NodeBuilderCustomizableContext nodeCustomizableContext = null; for (String s : splitted) { if (nodeDefinedContext == null) { nodeDefinedContext = builder.addNode(s); } else if (nodeCustomizableContext == null) { nodeCustomizableContext = nodeDefinedContext.addNode(s); } else { nodeCustomizableContext = nodeCustomizableContext.addNode(s); } } if (nodeDefinedContext == null) { builder.addConstraintViolation(); } else if (nodeCustomizableContext == null) { nodeDefinedContext.addConstraintViolation(); } else { nodeCustomizableContext.addConstraintViolation(); } }
@Override public boolean isValid(Map<String, String> map, ConstraintValidatorContext context) { for (String key : map.keySet()) { if (key == null || key.isEmpty()) { context.disableDefaultConstraintViolation(); // disable violation message context.buildConstraintViolationWithTemplate("key value cannot be null or empty").addConstraintViolation(); // add message return false; } if (map.get(key) == null || map.get(key).isEmpty()) { context.disableDefaultConstraintViolation(); // disable violation message context.buildConstraintViolationWithTemplate("value cannot be null or empty for key: " + key).addConstraintViolation(); // add message return false; } } return true; }
@Override public boolean isValid(CharSequence sequence, ConstraintValidatorContext context) { if (sequence == null || sequence.length() == 0) { return true; } final String value = sequence.toString(); for (String pattern : annotation.patterns()) { final DateFormat format = new SimpleDateFormat(pattern); format.setLenient(annotation.lenient()); try { format.parse(value); return true; } catch (@SuppressWarnings("unused") ParseException e) { continue; } } return false; }
private boolean validateRule(Object value, ConstraintValidatorContext ctx) { if (!(value instanceof Rule)) { addViolation(ctx, "Constraint valid only on instances of Rule."); return false; } boolean valid = true; Rule rule = (Rule) value; if (rule.getType() == RuleType.MOVE) { valid &= validateNotBlank(ctx, rule.getDestFolder(), "A destination folder must be specified."); } if (!isBlank(rule.getMatchingText())) { valid &= validateFields(ctx, rule); } else if (rule.getOlderThan() != null) { if (rule.getOlderThan() <= 0) { addViolation(ctx, "The age must be greater than 0."); valid = false; } } else if (rule.getOlderThan() == null) { addViolation(ctx, "Either matchingText or olderThan must be specified."); valid = false; } return valid; }
@Override public boolean isValid(Object value, ConstraintValidatorContext context) { try { String typeKey = (String) FieldUtils.readField(value, typeKeyField, true); if (value instanceof XmEntity) { return xmEntitySpecService.getAllKeys().containsKey(typeKey); } else { XmEntity entity = (XmEntity) FieldUtils.readField(value, entityField, true); if (entity == null) { return true; } String entityTypeKey = entity.getTypeKey(); Map<String, Set<String>> keysByEntityType = xmEntitySpecService.getAllKeys().get(entityTypeKey); return !(keysByEntityType == null || keysByEntityType.get(getClassName(value)) == null) && keysByEntityType.get(getClassName(value)).contains(typeKey); } } catch (IllegalAccessException e) { log.debug("Could not get keys for validation", e); return false; } }
@Override public boolean isValid(Object value, ConstraintValidatorContext ctx) { if (value == null) { addViolation(ctx, "Null values are not considered valid Rules"); return false; } boolean valid = true; if (value instanceof Collection) { for (Object o : ((Collection) value)) { valid &= validateRule(o, ctx); } } else { valid = validateRule(value, ctx); } return valid; }
@Override public boolean isValid(Object value, ConstraintValidatorContext context) { context.disableDefaultConstraintViolation(); try { String password = (String) ValidatorUtil.getFieldValue(value, passwordFieldName); String passwordVerification = (String) ValidatorUtil.getFieldValue(value, passwordVerificationFieldName); if (passwordsAreNotEqual(password, passwordVerification)) { ValidatorUtil.addValidationError(passwordFieldName, context); ValidatorUtil.addValidationError(passwordVerificationFieldName, context); return false; } } catch (Exception ex) { throw new RuntimeException("Exception occurred during validation", ex); } return true; }
@Override public boolean isValid(final String confirmCode, final ConstraintValidatorContext context) { return confirmCode != null && confirmCode.length() == 40; }
@Override public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) { if(StringUtils.isEmpty(s)) { return true; } else if(!valueList.contains(s)) { return false; } return true; }
@Override public boolean isValid(String string, ConstraintValidatorContext constraintValidatorContext) { if (type == null || type.length == 0 || (string == null && allowNull)) { return true; } return Arrays.binarySearch(type, string) >= 0; }
@Override public boolean isValid(String phoneNo, ConstraintValidatorContext ctx) { if(phoneNo == null){ return false; } //validate phone numbers of format "123456789" if (phoneNo.matches("\\d{9}")) return true; //return false if nothing matches the input else return false; }
private String getViolationMessages(Set<ConstraintViolation<Object>> violations, ConstraintValidatorContext ctx) { return violations.stream() .map(v -> v.getPropertyPath() + " : " + v.getMessage()) .sorted(String::compareTo) .reduce((v1, v2) -> v1 + ", " + v2) .orElse(ctx.getDefaultConstraintMessageTemplate()); }
@Override public boolean isValid(LocalDate localDate, ConstraintValidatorContext cxt) { // Another validator should check for this if required if (localDate == null) { return true; } return !localDate.isAfter(LocalDate.now()); }
@Override public boolean isValid(ConstraintValidatorContext context) { if (getExecutable() != null) { String error = GitCommand.checkError(getExecutable()); if (error != null) { context.disableDefaultConstraintViolation(); context.buildConstraintViolationWithTemplate(error).addConstraintViolation(); return false; } else { return true; } } else { return true; } }
@Override public boolean isValid(LocalDate localDate, ConstraintValidatorContext cxt) { // Another validator should check for this if required if (localDate == null) { return true; } long years = getAge(localDate); return years >= minYears && years <= maxYears; }
@Override public boolean isValid(LocalDate localDate, ConstraintValidatorContext cxt) { // Another validator should check for this if required if (localDate == null) { return true; } return !localDate.isBefore(LocalDate.now()); }
@Override default boolean isValid(T value, ConstraintValidatorContext context) { if (value == null) { return true; } return isValid(value); }
@Override public boolean isValid(String pathParam, ConstraintValidatorContext constraintValidatorContext) { if (StringUtils.isNotBlank(pathParam)) { if (appsService.isApplicationExists(pathParam)) { return true; } } log.warn("Couldn't find application: [" + pathParam + "]"); return false; }
public boolean isValid(VType value, VType[] possibleValues, BiFunction<VType, VType, Boolean> equalsMethod, ConstraintValidatorContext context) { for (VType possibleVal : possibleValues) { if (equalsMethod.apply(value, possibleVal)) { return true; } } return false; }
@Override public boolean isValid(String value, ConstraintValidatorContext context) { if (value == null) { return false; } return InetAddressValidator .getInstance() .isValidInet4Address(value); }
@Override public boolean isValid(final Object value, ConstraintValidatorContext context) { if (value == null || "".equals(value)) { return true; } else if (!StringUtil.isEmpty(validateRegexp.regexp())) { Pattern pattern = Pattern.compile(validateRegexp.regexp()); Matcher matcher = pattern.matcher(value.toString().replaceAll("/", "")); return matcher.matches(); } return false; }
@Override public boolean isValid(String value, ConstraintValidatorContext context) { if (value == null) { return false; } return InetAddressValidator .getInstance() .isValidInet6Address(value); }
@Override public boolean isValid(String value, ConstraintValidatorContext context) { if (isEmpty(value)) { return false; } SimpleDateFormat sdf = new SimpleDateFormat(annotation.value()); try { sdf.parse(value); return true; } catch (ParseException e) { return false; } }
@Override public boolean isValid(String value, ConstraintValidatorContext context) { Object[] enumValues = this.annotation.enumClass().getEnumConstants(); if (enumValues != null){ for (Object enumValue:enumValues){ if (value.equals(enumValue.toString())){ return true; } } } return false; }
@Override public boolean isValid(String email, ConstraintValidatorContext context) { EmailValidator emailValidator = EmailValidator.getInstance(); if((email == null) || (!emailValidator.isValid(email))) return false; return true; }