扩展数据校验
2019-07-11 本文已影响0人
jianshuqiang
定义注解
package com.sgcc.dls.imnotice.exam;
import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.Payload;
import javax.validation.constraints.Size;
import java.lang.annotation.Documented;
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.ElementType.TYPE_USE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = {})
public @interface IDCardValidator{
String message();
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
注解的实现类
package com.sgcc.dls.imnotice.exam;
import org.springframework.util.StringUtils;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
/**
* @title IDCardConstraintValidator
* @Description 描述 自定义注解
* @author zhangqiang
* @Date 2019年07月09日 14:30
* @Copyright 2019-2020 www.epri.sgcc.com.cn All rights reserved.
*/
public class IDCardConstraintValidator implements ConstraintValidator<IDCardValidator,String> {
@Override
public void initialize(IDCardValidator constraintAnnotation) {
}
@Override
public boolean isValid(String value, ConstraintValidatorContext context) {
String[] strings = StringUtils.delimitedListToStringArray(value, "-");
if(strings.length!=2){
return false;
}else{
return true;
}
}
}