I am trying to build a custom ValidationAttribute to validate the number of words for a given string:
public class WordCountValidator : ValidationAttribute
{
public override bool IsValid(object value, int count)
{
if (value != null)
{
var text = value.ToString();
MatchCollection words = Regex.Matches(text, @"[\S]+");
return words.Count <= count;
}
return false;
}
}
However, this does not work as IsValid() only allows for a single parameter, the value of the object being validated, so I can't override the method in this way.
Any ideas as to how I can accomplish this while still using the simple razor format:
[ViewModel]
[DisplayName("Essay")]
[WordCount(ErrorMessage = "You are over the word limit."), Words = 150]
public string DirectorEmail { get; set; }
[View]
@Html.ValidationMessageFor(model => model.Essay)