DefconDotNet

MinMaxStringLengthAttribute

Jan 10th, 2013
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.86 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Web.Mvc;
  5.  
  6. namespace IncassoBeheer.UI.Helpers.Filter
  7. {
  8.     /// <summary>
  9.     /// Specifies the minimum and maximum length of characters that are allowed in a data field.
  10.     /// </summary>
  11.     [AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
  12.     public class MinMaxStringLengthAttribute : StringLengthAttribute, IClientValidatable
  13.     {
  14.         public MinMaxStringLengthAttribute(int maximumLength, string errorMessage = "") : base(maximumLength)
  15.         {
  16.             ErrorMessage = errorMessage;
  17.         }
  18.  
  19.         public MinMaxStringLengthAttribute(int minimumLength , int maximumLength, string errorMessage="") : base(maximumLength)
  20.         {
  21.             MinimumLength = minimumLength;
  22.             ErrorMessage = errorMessage;
  23.         }
  24.  
  25.         public override string FormatErrorMessage(string name)
  26.         {
  27.             EnsureLegalLengths();
  28.             return String.IsNullOrWhiteSpace(ErrorMessage)
  29.                        ? String.Format("{0} moet minimum {1} en maximum {2} tekens bevatten.", name, MinimumLength, MaximumLength)
  30.                        : ErrorMessage;
  31.         }
  32.  
  33.         private void EnsureLegalLengths()
  34.         {
  35.             if (MaximumLength < 0)
  36.                 throw new InvalidOperationException("Maximum lengte kan niet lager zijn dan 0.");
  37.  
  38.             if (MaximumLength < MinimumLength)
  39.                 throw new InvalidOperationException("Minimum lengte kan niet hoger zijn dan de maximum lengte");
  40.         }
  41.  
  42.         public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
  43.         {
  44.             var adapt = new StringLengthAttributeAdapter(metadata, context, this);
  45.             return adapt.GetClientValidationRules();
  46.         }
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment