spring自定义校验注解
Posted 走路带_风
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring自定义校验注解相关的知识,希望对你有一定的参考价值。
自定义校验电话号码注解
@Target( ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE )
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = TelNumber.TelNumberValidator.class )
@Documented
public @interface TelNumber
String message() default "utils.validation.TelNumber.message";
Class<?>[] groups() default ;
Class<? extends Payload>[] payload() default ;
class TelNumberValidator implements ConstraintValidator<TelNumber, String>
private static final Pattern pattern = Pattern.compile("^1[3,4,5,7,8]\\\\d9$");
public void initialize(TelNumber constraintAnnotation)
public boolean isValid(String value, ConstraintValidatorContext context)
if (StringUtils.isEmpty(value))
return true;
Matcher m = pattern.matcher(value);
return m.matches();
自定义实现@MaxSize(size = 10)注解
@Target( ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE )
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MaxSize.MaxSizeValidator.class )
@Documented
public @interface MaxSize
String message() default "utils.validation.MaxSize.message";
long size() default 0;
Class<?>[] groups() default ;
Class<? extends Payload>[] payload() default ;
class MaxSizeValidator implements ConstraintValidator<MaxSize, String>
private long size;
public void initialize(MaxSize constraintAnnotation)
size = constraintAnnotation.size();
public boolean isValid(String value, ConstraintValidatorContext context)
if (value == null || value =="")
return true;
else
try
return value.length() <= size;
catch (Exception e)
e.printStackTrace();
return false;
以上是关于spring自定义校验注解的主要内容,如果未能解决你的问题,请参考以下文章