SpringValidator自定义验证实例:验证枚举类

自定义验证实例:验证枚举类

package com.yufan.all.valid.valid;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.FIELD,ElementType.METHOD,ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValue.Validator.class)
public @interface EnumValue {

    String message() default "枚举值不存在";

    Class[] groups() default {};

    Class[] payload() default {};

    int[] in() default {};



    /**
     *
     * 实现
     */
    class Validator implements ConstraintValidator {

        private Class> enumClass;
        private int[] in;
        private  Class[] groups;

        @Override
        public void initialize(EnumValue constraintAnnotation) {
            in = constraintAnnotation.in();
            groups = constraintAnnotation.groups();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            if(null==value){
                return false;
            }
            if(!(in.length>0)){
                return false;
            }
            for (int item :in){
                if(value.equals(item)){
                    return true;
                }
            }
            return false;
        }
    }


}

 

你可能感兴趣的:(SpringValidator自定义验证实例:验证枚举类)