自定义Validator检验数字类型

时间:2025-03-11 08:45:13

此文章主要是为了有个记录,方便以后使用,话不多说,直接上代码!!

1、添加一个校验的注解

package ;


import ;

import ;
import ;
import .*;

/**
 * @author huald
 * @date 2019/11/21
 */
@Documented
@Target({, })
@Retention()
@Constraint(validatedBy = )
public @interface CheckNumber {

    /**
     * @return size the element must be higher or equal to
     */
    int min() default 0;

    /**
     * @return size the element must be lower or equal to
     */
    int max() default Integer.MAX_VALUE;

    String message() default "当前字符串必须为数字类型";

    Class<?>[] groups() default {};


    Class<? extends Payload>[] payload() default {};
}

2、逻辑处理类

package ;

import ;
import ;
import .slf4j.Slf4j;

import ;
import ;

/**
 * 校验字符是否是数字且在要求范围内
 *
 * @author huald
 * @date 2019/11/21
 */
@Slf4j
public class CheckNumberValidator implements ConstraintValidator<CheckNumber, Object> {

    private CheckNumber checkNumber;

    @Override
    public void initialize(CheckNumber constraintAnnotation) {
         = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (value == null || (())) {
            //当参数值为null或者length = 0时,不做校验
            return true;
        }
        if (!(())) {
            return false;
        }
        try {
            int max = ();
            int min = ();
            int curValue = (());
            if (curValue < min || curValue > max) {
                return false;
            }
        } catch (NumberFormatException e) {
            return false;
        }
        return true;
    }

}

做个笔记,方便你我他!!