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ş
2009-04-29 15:42:43
Yes, any attribute which derives from ValidationAttribute will work.
Brad Wilson
2009-04-29 23:37:12
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
2010-04-23 15:33:40
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
2010-08-18 15:20:19