I have a Razor web page where I have a model
public class UploadModel
{
[Required]
[StringLength(25)]
public string PatientID { get; set; }
[DataType(DataType.Date)]
[DateRange("1000/12/01", "4010/12/16")]
public DateTime DrawDate { get; set; }
}
public class DateRangeAttribute : ValidationAttribute
{
private const string DateFormat = "yyyy/MM/dd";
private const string DefaultErrorMessage =
"'{0}' must be a date between {1:d} and {2:d}.";
public DateTime MinDate { get; set; }
public DateTime MaxDate { get; set; }
public DateRangeAttribute(string minDate, string maxDate)
: base(DefaultErrorMessage)
{
MinDate = ParseDate(minDate);
MaxDate = ParseDate(maxDate);
}
public override bool IsValid(object value)
{
if (value == null || !(value is DateTime))
{
return true;
}
DateTime dateValue = (DateTime)value;
return MinDate <= dateValue && dateValue <= MaxDate;
}
public override string FormatErrorMessage(string name)
{
return String.Format(CultureInfo.CurrentCulture,
ErrorMessageString,
name, MinDate, MaxDate);
}
private static DateTime ParseDate(string dateValue)
{
return DateTime.ParseExact(dateValue, DateFormat,
CultureInfo.InvariantCulture);
}
}
That does validation for the datetime
However in the view,
when I run through all the elements in the model
@Html.EditorFor(m => m)
It is creating a datetime type which creates problems because I am using jquery to do the calendar date picking since it is cross broswer. Any way to force the datetime to become a text even with the validation class? Thanks!
Since you are writing your custom validation, why don’t you change
to a string type and adjust your validation accordingly?