package com.junmp.jyzb.api.bean.validator;

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

public class IsDateTimeValidator implements ConstraintValidator<IsDateTime, String> {


    private String format;

    @Override
    public void initialize(IsDateTime constraintAnnotation) {
        this.format = constraintAnnotation.format();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null) {
            return true; // 允许字段为空
        }

        SimpleDateFormat sdf = new SimpleDateFormat(format);
        sdf.setLenient(false); // 不允许宽松解析日期

        try {
            sdf.parse(value);
            return true; // 字段是有效的日期或时间
        } catch (ParseException e) {
            return false; // 字段不是有效的日期或时间
        }
    }
}
