The DataTypeAttributes available are great, but sometimes you might want to create your own, and so i hope you'll be pleased to learn it's actually really simple to do so:
The example code below is for a custom MaxLength attribute for a text property:
Usage:
  [MaxLength(Length=2, ErrorMessage="Text is to long")]
  public string sample { get; set; }
Code:
namespace DiscMaster.Web.Models.DataAnnotations
{
    [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
    public class MaxLengthAttribute : DataTypeAttribute
    {
        public int Length { get; set; }
        public MaxLengthAttribute() : base(DataType.Text)
        {
        }
        public override bool IsValid(object value)
       {
            string str = Convert.ToString(value, CultureInfo.CurrentCulture);
            if (string.IsNullOrEmpty(str))
                return true;
            if (str.Length > Length)
            {
                return false;
            }
            return true;
        }
    }
}
As always, Codename 'DiscMaster' can be found at: http://discmaster.codeplex.com/
Best regards,
P.
 
 
No comments:
Post a Comment