package com.njcn.web.config;

import cn.hutool.core.util.StrUtil;
import com.njcn.web.pojo.annotation.DateTimeStrValid;

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

/**
 * pqs
 *
 * @author cdf
 * @date 2022/1/11
 */
public class DateTimeValidator implements ConstraintValidator<DateTimeStrValid, String> {
    private DateTimeStrValid dateTime;
    @Override
    public void initialize(DateTimeStrValid dateTime) {
        this.dateTime = dateTime;
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (StrUtil.isBlank(value)) {
            return true;
        }
        String format = dateTime.format();

        if (value.length() != format.length()) {
            return false;
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);

        try {
            simpleDateFormat.parse(value);
        } catch (Exception e) {
            return false;
        }
        return true;
    }
}
