1.传入指定时间格式判断是否为有效时间
public class IsDateOk : ValidationAttribute
{
private string _dateFormatter;
public IsDateOk(string DateFormatter)
{
_dateFormatter = DateFormatter;
}
public override bool IsValid(object value)
{
var isValid = false;
if (value == null) return false;
if (DateTime.TryParseExact((string)value, _dateFormatter, CultureInfo.CurrentCulture,
DateTimeStyles.None, out DateTime dateValue))
{
isValid = true;
}
return isValid;
}
}
2.传入指定时间是否小于当前时间
public class IsGreaterThan : ValidationAttribute
{
public string OtherProperty { get; }
public IsGreaterThan(string otherProperty) : base()
{
OtherProperty = otherProperty ?? throw new ArgumentNullException(nameof(otherProperty));
}
protected override ValidationResult IsValid(object value,ValidationContext validationContext)
{
var otherPropertyInfo = validationContext.ObjectType.GetRuntimeProperty(OtherProperty);
var otherPropertyValue = otherPropertyInfo.GetValue(validationContext.ObjectInstance, null);
if (!DateTime.TryParseExact((string)value, "HH:mm", CultureInfo.CurrentCulture,
DateTimeStyles.None, out DateTime endTime)) throw new UserFriendlyException($"{value}无效");
if (!DateTime.TryParseExact((string)otherPropertyValue, "HH:mm", CultureInfo.CurrentCulture,
DateTimeStyles.None, out DateTime startTime)) throw new UserFriendlyException($"{otherPropertyValue}无效");
if (DateTime.Compare(startTime, endTime)>0)
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
}
3.使用
[Required]
[MaxLength(10)]
[IsDateOk(DateFormatter: "HH:mm",ErrorMessage = "早班开始时间无效")]
public string MorningShiftStartTime { get; set; }
[Required]
[MaxLength(10)]
[IsDateOk(DateFormatter: "HH:mm", ErrorMessage = "早班结束时间无效")]
[IsGreaterThan("MorningShiftStartTime", ErrorMessage = "早班结束时间小于开始时间")]
public string MorningShiftEndTime { get; set; }