首页 > 技术文章 > 设定范围和步长的递增数验证器Validator

feika 2015-04-20 14:55 原文

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;
    }
}

 

推荐阅读