package com.hdkj.lt.base.constraints;

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

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;

/**
 * @Description: 日期时间字符串校验器
 * @Author: wenhao
 * @Create: 2021/10/20 11:16
 * @Version: 1.0
 */
public class DateTimeValidator implements ConstraintValidator<DateTimeValid, String> {

    private DateTimeValid dateTimeValid;

    @Override
    public void initialize(DateTimeValid dateTimeValid) {
        this.dateTimeValid = dateTimeValid;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 如果value为空则不进行格式验证，为空验证可以使用 @NotBlank @NotNull @NotEmpty 等注解来进行控制，职责分离
        if (StringUtils.isBlank(value)) {
            return true;
        }
        String format = dateTimeValid.format();
        if (value.length() != format.length()) {
            return false;
        }
        try {
            new SimpleDateFormat(format).parse(value);
        } catch (ParseException e) {
            return false;
        }
        return true;
    }

}
