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({FIELD})
@Retention(RUNTIME)
@Documented
@Constraint(validatedBy = NotStrSpecialValidator.class)
public @interface NotStrSpecial {
String message() default "the str has special char. ";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 特殊字符验校验器
*/
public class NotStrSpecialValidator implements ConstraintValidator<NotStrSpecial, Object> {
@Override
public void initialize(NotStrSpecial constraintAnnotation) {}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if(value==null){
return false;
}
String str = value.toString();
if(str == null){
return false;
}
if(isSpecialChar(str)){
return false;
}
return true;
}
public static boolean isSpecialChar(String str) {
String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\n|\r|\t";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.find();
}
}