SpringBoot自定义validation验证
java1234
共 811字,需浏览 2分钟
·
2020-12-18 15:25
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
作者 | Se7end
来源 | urlify.cn/FRJ7Fv
注解类
import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = StringLengthValidator.class)
public @interface StringLength {
// 必须加
String message() default "{javax.validation.constraints.NotNull.message}";
// 必须加
Class>[] groups() default {};
// 必须加
Class extends Payload>[] payload() default {};
int minLength() default 0;
int maxLength() default 16;
}
验证实现类
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Objects;
public class StringLengthValidator implements ConstraintValidator {
private StringLength stringLength;
@Override
public void initialize(StringLength constraintAnnotation) {
this.stringLength = constraintAnnotation;
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (Objects.isNull(value)) {
return true;
}
if (null != stringLength) {
int length = String.valueOf(value).length();
int maxLen = stringLength.maxLength(),
minLen = stringLength.minLength();
return length >= minLen && length <= maxLen;
}
return false;
}
}
粉丝福利:Java从入门到入土学习路线图
???
?长按上方微信二维码 2 秒
感谢点赞支持下哈
评论