package com.kxs.common.core.valid.impl;

import com.kxs.common.core.valid.Sn;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * sn格式校验器
 *
 * @author 没秃顶的码农
 * @date 2024-04-11
 */
public class SnValidator implements ConstraintValidator<Sn, String> {

    // 注解对象
    private Sn sn;

    // 初始化【sn】对象
    @Override
    public void initialize(Sn constraintAnnotation) {
        sn = constraintAnnotation;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || value.isEmpty()){
            return false;
        }
        // 获取【sn】对象的手机格式验证表达式
        String pattern = sn.pattern();
        Pattern compile = Pattern.compile(pattern);
        Matcher matcher = compile.matcher(value);
        return matcher.matches();
    }
}

