In an Asp.net MVC app, I have inherited this problem (if it is a problem?) where one developer has used String
for Date type.
In my model the property reads:
[Required]
[DisplayName("Registration Date")]
public string Registrationdate { get; set; }
The business requirement is that the field is not required, but if there is something in that fields then it must be a valid date.
How would you implement this requirement, without changing the data type?
It looks like you're using System.ComponentModel.DataAnnotations
. The best way to do this using this library would be to create a new attribute to validate date strings and apply it to the property. Here's some code for you to start with:
[AttributeUsage(AttributeTargets.Property, Inherited = true)]
class DateAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
var dateString = value as string;
if (string.IsNullOrWhiteSpace(dateString))
{
return true; // Not our problem
}
DateTime result;
var success = DateTime.TryParse(dateString, out result);
return success;
}
}
You'll probably want to expand on this code depending on what kind of strings you're expecting from the client. Also, this won't give you any client-side validation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With