想验证前端传入对象的Integer属性
1.新建一个注解类 @FlagValidator
import javax.validation.Constraint; import javax.validation.Payload; import java.lang.annotation.*; /** * 用户验证状态是否在指定范围内的注解 */ @Documented @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD,ElementType.PARAMETER}) @Constraint(validatedBy = FlagValidatorClass.class) public @interface FlagValidator { String[] value() default {}; String message() default "flag is not found"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {}; }
2.新建一个类继承实现ConstraintValidator
import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; /** * @Description TODO * @Author xjy * @Date 2019/9/29 */ public class FlagValidatorClass implements ConstraintValidator<FlagValidator, Integer> { private String[] values; @Override public void initialize(FlagValidator flagValidator) { values = flagValidator.value(); } //下面的判断逻辑,values是注解里面的值, value 是属性的值 @Override public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) { boolean isValid = false; if (value == null){ return true; } for (int i = 0; i < values.length; i++) { if (values[i].equals(String.valueOf(value))){ isValid = true; break; } } return isValid; } }
3.使用
@FlagValidator(value = {"1", "5"}, message = "请输入正确的状态") private Integer status = 1;
原文地址:https://www.cnblogs.com/418836844qqcom/p/11640810.html
时间: 2024-11-11 18:39:30