Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate date when using `String` instead of a `Date` type?

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?

like image 963
VoodooChild Avatar asked Feb 02 '11 22:02

VoodooChild


1 Answers

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.

like image 61
Brant Bobby Avatar answered Oct 20 '22 00:10

Brant Bobby