Tuesday, October 27, 2009

Codename 'DiscMaster' - Implementing a custom DataTypeAttribute

In MVC the default validation is provided by DataAnnotations (this is, of course, replaceable) and is fantastic if you ask me. Being able to define the validation principles at the scope of the Model instead of UI makes a much more friendly architecture and enables the controller to present it's data to any view imaginable while still holding together beneath it all.

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: