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

com.neko233.toolchain.validator.impl.NumberValidator Maven / Gradle / Ivy

package com.neko233.toolchain.validator.impl;

import com.neko233.toolchain.common.base.StringUtils233;
import com.neko233.toolchain.validator.ValidateApi;
import com.neko233.toolchain.validator.annotation.Number;

import java.util.Objects;

/**
 * ValidateNumber Validator
 */
public class NumberValidator implements ValidateApi {

    @Override
    public Class getAnnotationType() {
        return Number.class;
    }

    @Override
    public boolean validateOk(Number annotation, java.lang.Number fieldValue) {

        if (fieldValue == null) {
            return false;
        }

        int intValue = fieldValue.intValue();
        // 负整数
        if (annotation.isMustNegative()) {
            if (intValue > 0) {
                return false;
            }
        }
        // 正整数
        if (annotation.isMustPositive()) {
            if (intValue < 0) {
                return false;
            }
        }

        int min = annotation.min();
        int max = annotation.max();

        if (min == 0 && max == 0) {
            return true;
        }

        int value = intValue;
        if (value < min) {
            return false;
        }
        if (value > max) {
            return false;
        }
        int[] excludeNumber = annotation.excludeNumber();
        if (excludeNumber != null) {
            for (int i : excludeNumber) {
                if (Objects.equals(i, fieldValue)) {
                    return false;
                }
            }
        }

        return true;
    }

    @Override
    public String getReason(Number annotation, String fieldName, java.lang.Number fieldValue) {
        return StringUtils233.format("tips = {}. field = {}. value is {}", annotation.tips(), fieldName, fieldValue);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy