package com.hdkj.lt.base.constraints;

import com.hdkj.lt.base.annotations.SpecialCharValid;
import org.apache.commons.lang3.StringUtils;

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

/**
 * @Description: 字符串特殊字符校验器（\ / : * ? " < > |）
 * @Author: wucx
 * @Create: 2022/10/17 14:26
 * @Version: 1.0
 */
public class SpecialCharValidator implements ConstraintValidator<SpecialCharValid, String> {

    private final Pattern PATTERN = Pattern.compile("[\\:*?\"<>|/]");
    private SpecialCharValid specialCharValid;

    @Override
    public void initialize(SpecialCharValid specialCharValid) {
        this.specialCharValid = specialCharValid;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext constraintValidatorContext) {
        // 如果value为空则不进行格式验证，为空验证可以使用 @NotBlank @NotNull @NotEmpty 等注解来进行控制，职责分离
        if (StringUtils.isBlank(value)) {
            return true;
        }
        constraintValidatorContext.disableDefaultConstraintViolation();
        String result = String.format("%s%s", specialCharValid.fieldName(), specialCharValid.message());
        constraintValidatorContext.buildConstraintViolationWithTemplate(result).addConstraintViolation();
        // 校验指定值是否包含特殊字符
        Matcher matcher = PATTERN.matcher(value);
        return !matcher.find();
    }

}
