zoukankan      html  css  js  c++  java
  • 设定范围和步长的递增数验证器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;
        }
    }
  • 相关阅读:
    ReverseFind的用法 ; 查找字符中最后一个字符
    sprintf_s() 、sprintf()和printf()区别和用法
    CString/string 区别及其转化
    CC++中strcat()函数
    C++中cstring.h和string.h的区别
    vs中CString的用法,以及所需的头文件
    头文件afx.h作用
    sprintf_s函数用法
    C++ format 函数
    C/C++ typedef用法
  • 原文地址:https://www.cnblogs.com/feika/p/4441593.html
Copyright © 2011-2022 走看看