Eric Brown - Cal
Eric Brown - Cal

Reputation: 14379

Extending the DataAnnotations attributes for MVC in asp.net

Brad Willson has a great article on descripting how to use DataAnnotations. http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html What I would like to do is extend the available attributes that I can use. Something like [ PastDate(you must enter a date in the past)] or [InvoiceNumber( all invoices start with INV and end with 002)]. I know that I could use the Regular expression attribute to accomplish this. However having more descriptive attributes would be a cleaner solution.

Upvotes: 0

Views: 2082

Answers (2)

Jeremy Gruenwald
Jeremy Gruenwald

Reputation: 1957

I have a few of these in my project - some still use regular expressions, but at least this way they're only in one place:

public class TelephoneAttribute : RegularExpressionAttribute
{
    public TelephoneAttribute()
        : base(@"^\(?(\d{3}\)?)((-| )?\d{3})(-?\d{4})$") { }
}

And more like what your example:

public class MinimumDateAttribute : RangeAttribute
{
    public MinimumDateAttribute(string MinimumDate)
        : base(typeof(DateTime), MinimumDate, DateTime.MaxValue.ToShortDateString()) { }
}

Upvotes: 0

Çağdaş Tekin
Çağdaş Tekin

Reputation: 16651

You need to create a class that inherits from System.ComponentModel.DataAnnotations.ValidationAttribute and then use that attribute like this :

public class yourModel {
    [CustomValidation(typeof(yourClass), "yourMethod")]
    public int yourProperty { get; set; }
}

Haven't tried it but it should work.

Upvotes: 1

Related Questions