Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 770
Baxter Avatar asked Dec 03 '25 17:12

Baxter


1 Answers

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?

like image 99
Matt G. Avatar answered Dec 06 '25 07:12

Matt G.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!