MVC 2 Validation
25 August 2010The 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;
}
}