• 设定范围和步长的递增数验证器Validator


    1、接口注释

    @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
    @Retention(RUNTIME)
    @Documented
    @Constraint(validatedBy = {IncrementalValidator.class})
    public @interface IncrementalInteger {
    
        String message() default "{common.incrementalInteger.Pattern}";
    
        Class<?>[] groups() default {};
    
        Class<? extends Payload>[] payload() default {};
    
        /**
         * @return value the element must be larger or equal to
         */
        int min();
        
        /**
         * @return value the element must be smaller or equal to 
         */
        int max();
    
        /**
         * @return value must be incremental
         */
        int increment();
    
        /**
         * Defines several {@link IncrementalInteger} annotations on the same
         * element.
         *
         * @see IncrementalInteger
         */
        @Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
        @Retention(RUNTIME)
        @Documented
        @interface List {
    
            IncrementalInteger[] value();
        }
    }

    2、Validator类

    public class IncrementalValidator implements ConstraintValidator<IncrementalInteger, Integer> {
    
        private IncrementalInteger constraintAnnotation;
    
        @Override
        public void initialize(IncrementalInteger constraintAnnotation) {
            this.constraintAnnotation = constraintAnnotation;
        }
    
        @Override
        public boolean isValid(Integer value, ConstraintValidatorContext context) {
            int min = constraintAnnotation.min();
            int increment = constraintAnnotation.increment();
            int max = constraintAnnotation.max();
            if (value < min) {
                return false;
            }
    
            if (value > max) {
                return false;
            }
    
            if ((value - min) % increment != 0) {
                return false;
            }
    
            return true;
        }
    }
  • 相关阅读:
    Ubuntu系统下的实用软件推荐
    上传项目到GitHub
    eclipse+fileSyncPlugin+svn+jenkins+tomcat
    js,jq获取元素位置属性及兼容性写法
    清除浮动的几种方法
    sub,dl,dt,排版,横向滚动条,浮动元素居中,box-sizing
    a里面不能嵌套a
    随笔
    自适应屏幕轮播图详解
    tip
  • 原文地址:https://www.cnblogs.com/feika/p/4441593.html
Copyright © 2020-2023  润新知