All Downloads are FREE. Search and download functionalities are using the official Maven repository.

io.convergence_platform.common.validations.MinimumLengthValidator Maven / Gradle / Ivy

Go to download

Holds the common functionality needed by all Convergence Platform-based services written in Java.

The newest version!
package io.convergence_platform.common.validations;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.lang.reflect.Array;
import java.util.List;

public class MinimumLengthValidator implements ConstraintValidator {
    private int value;

    public static void pathVariable(String value, int length, String varName) {
        boolean valid = true;
        if ("".equals(value)) {
            valid = false;
        } else {
            valid = validate(value, length);
        }

        ValidationHelper.raiseValidationErrorForPathVariable(valid, "min_length", varName);
    }

    @Override
    public void initialize(MinimumLength constraintAnnotation) {
        ConstraintValidator.super.initialize(constraintAnnotation);
        value = constraintAnnotation.value();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        return validate(value, this.value);
    }

    private static boolean validate(Object value, int size) {
        if (value == null) {
            return false;
        }

        if (value instanceof List) {
            return ((List) value).size() >= size;
        } else if (value.getClass().isArray()) {
            return Array.getLength(value) >= size;
        } else if (value instanceof CharSequence) {
            return ((CharSequence) value).length() >= size;
        }

        return false;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy