package com.ruoyi.ext.api.validate;

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.regex.Pattern;

/**
 * 自定义汉字校验注解实现
 * 
 * @author ruoyi
 */
public class ChineseValidator implements ConstraintValidator<ChineseV, String>
{
    String pattern;
    Pattern compile;

    @Override
    public void initialize(ChineseV constraintAnnotation) {
//        pattern = "^[\\u0391-\\uFFE5]|[·]+$";
        pattern = "[\u4e00-\u9fa5]";
        compile = Pattern.compile(pattern);
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StringUtils.isBlank(value)){
            return true;
        }
        return Arrays.stream(value.split("")).allMatch(s -> compile.matcher(s).matches());
    }
}