Unicode校验
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UnicodeMaxImpl.class)
public @interface UnicodeMax {
    int minLength();
    int maxLength();
    String message() default "数据长度不合法!";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}
校验实现逻辑
public class UnicodeMaxImpl implements ConstraintValidator<UnicodeMax, String> {
    private int minLength;
    private int maxLength;
    @Override
    public void initialize(UnicodeMax constraintAnnotation) {
        this.maxLength = constraintAnnotation.maxLength();
        this.minLength = constraintAnnotation.minLength();
    }
    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isEmpty(value)) {
            return true;
        }
        int length = getCharLength(value);
        if (length < minLength || length > maxLength) {
            return false;
        }
        return true;
        //return Pattern.matches("^(([\\u4e00-\\u9fa5]|[\\w\\s]|[\\pP|\\pS])*)?$", value);
    }
    public static int getCharLength(String value){
        int halfCharCount = 0;
        int allCharCount = 0;
        char[] chars = value.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            String temp = String.valueOf(chars[i]);
            /**
             * 判断是全角字符
             */
            if (temp.matches("[^\\x00-\\xff]")) {
                allCharCount ++;
            }
            /**
             *  判断是半角字符
             */
            else {
                halfCharCount ++;
            }
        }
        return halfCharCount + 2 * allCharCount;
    }
}
^(([\\u4e00-\\u9fa5]|[\\w\\s]|[\\pP|\\pS])*)?$
url:全角半角逻辑-> https://blog.csdn.net/u012815136/article/details/81408165








网友评论