package com.changhu.common.validator;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.changhu.common.validator.annotation.IsMobile;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * author: luozhun
 * desc: IsMobileValidator
 * createTime: 2023/8/22 9:38
 */
public class IsMobileValidator implements ConstraintValidator<IsMobile, String> {
    private boolean required;

    @Override
    public void initialize(IsMobile constraintAnnotation) {
        //初始化时先获取他是否为必填信息
        required = constraintAnnotation.required();
    }

    @Override
    public boolean isValid(String s, ConstraintValidatorContext constraintValidatorContext) {
        if (required) {
            //必填则校验手机号
            return Validator.isMobile(s);
        } else {
            //非必填直接返回ture
            if (StrUtil.isBlank(s)) {
                return true;
            } else {
                return Validator.isMobile(s);
            }
        }
    }
}
