型號:
[DateCorrectRange(ValidateStartDate = true, ErrorMessage = "Start date shouldn't be older than the current date")]
public DateTime StartDate { get; set; }
[DateCorrectRange(ValidateEndDate = true, ErrorMessage = "End date can't be younger than start date")]
public DateTime EndDate { get; set; }
屬性類:
[AttributeUsage(AttributeTargets.Property)]
public class DateCorrectRangeAttribute : ValidationAttribute
{
public bool ValidateStartDate { get; set; }
public bool ValidateEndDate { get; set; }
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var model = validationContext.ObjectInstance as YourModelType;
if (model != null)
{
if (model.StartDate > model.EndDate && ValidateEndDate
|| model.StartDate > DateTime.Now.Date && ValidateStartDate)
{
return new ValidationResult(string.Empty);
}
}
return ValidationResult.Success;
}
}
你爲什麼要使用*屬性*?您希望什麼時候應用它?作爲驗證? –
我相信應該通過驗證庫在客戶端驗證。然後,爲了安全起見,您可以在後端進行驗證,向模型狀態添加錯誤。 – TNCodeMonkey
你爲什麼要比較?你的目的是限制一方的價值嗎?你可以嘗試搜索'強制',這就是它在WPF中的調用方式。不幸的是不能幫助你與asp.net。 –