【发布时间】:2018-09-23 16:34:24
【问题描述】:
我在date 属性上引入了两个注解。一种是验证日期范围(例如从 1 天后到 15 天后),另一种是验证时间范围(例如从上午 8.30 到下午 4.30)。如果值都不满足这两个验证,我希望网页提示CustomDateRange而不是CustomTimeRange的错误消息。目前,情况正好相反。
[Required]
[CustomDateRange(ErrorMessage = "Your reservation time should be at least 24 hours and at most 15 days in advance.")]
[CustomTimeRange]
public DateTime? date { get; set; }
public class CustomDateRangeAttribute : RangeAttribute
{
public CustomDateRangeAttribute() : base(typeof(DateTime), DateTime.Now.AddDays(1).ToString(), DateTime.Now.AddDays(15).ToString())
{ }
}
public class CustomTimeRangeAttribute : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
try
{
DateTime dt = (DateTime)value;
TimeSpan ts = dt.TimeOfDay;
TimeSpan start = new TimeSpan(8, 30, 0);
TimeSpan end = new TimeSpan(16, 30, 0);
if (ts >= start && ts <= end)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult("Your reservation time should be with in the openning hours, which is from 8.30am to 4:30pm.");
}
}
catch (Exception e)
{
return new ValidationResult("Invalid time input!");
}
}
}
【问题讨论】:
-
我猜你必须有一个特殊的组合属性,然后你才能控制顺序和错误信息。
标签: c# asp.net asp.net-mvc validation