设定范围和步长的递增数验证器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;
}
}
上一篇:FPGA+x86构建高性能国产网络测试仪竞技之道


下一篇:2000条你应知的WPF小姿势 基础篇<22-27 WPF生命周期, 基础类等>