tags:

views:

330

answers:

3

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.

+1  A: 

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.

çağdaş
Yes, any attribute which derives from ValidationAttribute will work.
Brad Wilson
A: 

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()) { }
}
Jeremy Gruenwald
A: 

For some reason I'm trying to add this on my project and it won't work:

public class YearRangeAttribute : RangeAttribute
    {
        public YearRangeAttribute()
            : base(typeof(DateTime), DateTime.Now.AddYears(-100).Year.ToString(), DateTime.Now.AddYears(-14).Year.ToString()) { }
    }

Could anyone kindly point out why? We can't use constant for the years here as these years will change when the application runs for several years.

Your suggestions are more than welcome.

Lizet

Lizet