基于mybatisPlus的特殊字符校验
要实现以下代码前提是导入Mybatis-plus的jar:
* @author WENGKAIBO505 */ @Target({ElementType.FIELD, ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Constraint(validatedBy=SpecialFieldValidator.class) public @interface SpecialField { String message() default "不能包含特殊字符"; Class<?>[] groups() default {}; Class<? extends Payload>[] payload() default {};
ackage com.paic.ocss.gateway.model.validator; import javax.validation.ConstraintValidator; import javax.validation.ConstraintValidatorContext; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * @author WENGKAIBO505 */ public class SpecialFieldValidator implements ConstraintValidator<SpecialField, String> { /** * 特殊字符的正则表达式 */ private String reg = "[_`~!@#$%^&*()+=|{}':;',\\\\[\\\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]|\\n|\\r|\\t"; private Pattern pt = Pattern.compile(reg); @Override public void initialize(SpecialField specialField) { // TODO Auto-generated method stub } @Override public boolean isValid(String value, ConstraintValidatorContext arg1) { if (value == null) { return true; } Matcher m = pt.matcher(value); if (m.find()) { return false; } return true; } }