Custom date validation with ASP.NET MVC / Web-Api server and client-side dutch date example

I live in the Netherlands and we have a different way of writing the date then like in the US. For example: 31 January 2012 is like this: 31-01-2012.

To accomplish this to be validated with MVC and Web-Api add a class that will act as an attribute to your project that has the following code:

    public class DutchDateAttribute : RegularExpressionAttribute {       

        static DutchDateAttribute()
            // necessary to enable client side validation
            DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(DutchDateAttribute), typeof(RegularExpressionAttributeAdapter));

        public DutchDateAttribute() : base(@"^([0-9]{1,2})-([0-9]{1,2})-([0-9]{4,4})$")

        public override bool IsValid(object value)
            return true;

Then apply this to your model/viewmodel that containts the DateTime property:

        [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
        [DutchDateAttribute(ErrorMessage = "Voer een geldige datum in./Enter a valid date")]
        public DateTime StartDate { get; set; }

That’s it! If you use the default jquery.validate.unobtrusive from Microsoft this will be applied as serverside and client side logic.

The only part that is a somewhat strange for me is the override of the IsValid method that always returns true… Maybe somebody that is reading this can explain that to me? I tried to tamper with the date like 50-07-2012 and it was not validated, so that the server validated is still in place even of the return true code.

Note: The regular expression may no be sufficient enough to exclude every situation and possibly can be enhanced.

This entry was posted in ASP.NET, JavaScript, MVC, Web-Api. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s