I have a metadata class for my Customer
where I validate the PurchaseDate
.
- The first annotation (
DataType
) is for formatting the date in anEditorFor
, to show just the date part. - The second annotation is a custom validation to verify that the value is a DateTime, including a custom error message.
My problem is that the first annotation will cancel out the errormessage of the second annotation.
Is it possible to combine these two using only data annotations? Or do I have to format the date in the EditorFor
?
[MetadataType(typeof(Customer_Metadata))]
public partial class Customer { }
public class Customer_Metadata
{
[DataType(DataType.Date)]
[MyDate(ErrorMessage = "Invalid purchase date")]
public DateTime? PurchaseDate { get; set; }
}
The same problem occurs if I try to replace the [DataType(DataType.Date)]
with
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
I won't get my custom error message.
EDIT
My main goal is to have a custom error message while also only showing the date part in the rendered input field. Is it possible with only data annotations?
Here's the MyDate
attribute:
public class MyDate : ValidationAttribute
{
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
DateTime dt;
var test = DateTime.TryParse((value ?? string.Empty).ToString(), out dt);
if (test)
{
return ValidationResult.Success;
}
else
{
return new ValidationResult(ErrorMessage);
}
}
}