Reputation: 481
I introduced two annotations on date
attribute. One is to validate the date range (e.g. from 1 days later to 15 days later), the other is to validate the time range (e.g. from 8.30am to 4.30pm). If the value meets neither of the two validations, I want the web page to prompt the errormessage of CustomDateRange
rather than CustomTimeRange
. For now, the opposite situation happens.
[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!");
}
}
}
Upvotes: 0
Views: 647
Reputation: 143
Why not to display both errors in validation summary? Check this out - http://www.tutorialsteacher.com/mvc/htmlhelper-validationsummary
So when one error is completed, say Time, at save there will be only one error displayed.
Or you could display each error message below your date widget like this
@Html.ValidationMessageFor(model => model.CustomDateRange)
@Html.EditorFor(model => model.CustomDateRange)
...
@Html.ValidationMessageFor(model => model.CustomTimeRange)
@Html.EditorFor(model => model.CustomTimeRange)
But, displaying one error at moment is not good practice, users than have to click Save button lets say 5 times to correct one error at time before final error-clear save is commited.
Upvotes: 1