Profile picture

Gareth Hughes MVC 2 Validation

MVC 2 Validation

25 August 2010

The first release of this website had a rather clunky validation system that I created, it was made without much knowledge of MVC 2. I've been brushing up on my MVC 2 and switched to using validation attributes on my view models.

It covers the basics, required, regex, length etc. But I wanted a rule to determine the length of a string provided by a WYSIWYG editor. The WYSIWYG will have extra whitespace characters and HTML which need to be stripped.

This is what I came up with to solve this problem, there may be an easier way. (This needs an implemented StripHtml extension method to work.)

public class RequiredHtml: ValidationAttribute
{
  private int maxLength = int.MaxValue;
  private int minLength;

  public int MinLength
  {
    get { return minLength; }
    set { minLength = value; }
  }

  public int MaxLength
  {
    get { return maxLength; }
    set { maxLength = value; }
  }

  public override bool IsValid( object value )
  {
    if ( value == null )
      return false;

    var strLength = value.ToString().StripHtml().Trim().Length;
    return strLength >= minLength && strLength <= maxLength;
  }
}
blog comments powered by Disqus

About Me

Software Developer from Sheffield, England with a first class degree in Software Engineering. Specialising in .NET, JavaScript and PHP.

This is my blog about random things, usually nerdy. I enjoy gaming, reading, music, football and cycling.

Search

Social Stream

Contact Me