示例代码:
public class MyModel { [Required] public DateTime StartDate { get; set; }
[Required]
[GreaterThan(nameof(StartDate), ErrorMessage = "EndDate must be greater than StartDate.")]
public DateTime EndDate { get; set; }
}
示例代码:
public class GreaterThanAttribute : ValidationAttribute { private readonly string _comparisonProperty;
public GreaterThanAttribute(string comparisonProperty)
{
_comparisonProperty = comparisonProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(_comparisonProperty);
if (property == null)
{
return new ValidationResult($"Property {_comparisonProperty} not found.");
}
var comparisonValue = property.GetValue(validationContext.ObjectInstance, null);
if (comparisonValue != null && value != null && (DateTime)value <= (DateTime)comparisonValue)
{
return new ValidationResult(ErrorMessage);
}
return ValidationResult.Success;
}
}
在模型类中使用自定义数据注解。
示例代码:
public class MyModel { [Required] public DateTime StartDate { get; set; }
[Required]
[GreaterThan(nameof(StartDate), ErrorMessage = "EndDate must be greater than StartDate.")]
public DateTime EndDate { get; set; }
}
然后,只需使用ModelState.IsValid来验证模型是否有效。