3

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)

1 Answer 1

6

I might be missing something obvious -- that happens to me a lot -- but could you not save the maximum word count as an instance variable in the constructor of WordCountValidator? Sort of like this:

public class WordCountValidator : ValidationAttribute
{
    readonly int _maximumWordCount;

    public WordCountValidator(int words)
    {
        _maximumWordCount = words;
    }

    // ...
}

That way when you call IsValid(), the maximum word count is available to you for validation purposes. Does this make sense, or like I said, am I missing something?

Sign up to request clarification or add additional context in comments.

2 Comments

That works perfectly! After setting up the constructor as you demonstrated I was able to simply add the new custom validator as an annotation for the field: [WordCountValidator(150, ErrorMessage = "Over the allowed word limit")]
Glad to hear :-) I guess sometimes the best solutions are the simple ones!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.