Baxter
Baxter

Reputation: 5825

Custom Validation Attribute With Multiple Parameters

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)

Upvotes: 3

Views: 11553

Answers (1)

Matt G.
Matt G.

Reputation: 1762

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?

Upvotes: 6

Related Questions