C# 具有多个参数的自定义验证属性

C# 具有多个参数的自定义验证属性,c#,asp.net-mvc,validation,razor,C#,Asp.net Mvc,Validation,Razor,我正在尝试构建自定义ValidationAttribute以验证给定字符串的字数: public class WordCountValidator : ValidationAttribute { public override bool IsValid(object value, int count) { if (value != null) { var text = value.ToString();

我正在尝试构建自定义ValidationAttribute以验证给定字符串的字数:

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;
    }
}

我可能遗漏了一些显而易见的东西——这在我身上经常发生——但是您能不能在WordCountValidator的构造函数中将最大字数保存为实例变量?有点像这样:

public class WordCountValidator : ValidationAttribute
{
    readonly int _maximumWordCount;

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

    // ...
}

这样,当您调用
IsValid()
时,就可以使用最大字数进行验证。这有意义吗?或者像我说的,我遗漏了什么吗?

这非常有效!在您演示了如何设置构造函数之后,我可以简单地添加新的自定义验证器作为字段的注释:[WordCountValidator(150,ErrorMessage=“Over the allowed word limit”)]很高兴听到:-)我想有时候最好的解决方案是简单的!
public class WordCountValidator : ValidationAttribute
{
    readonly int _maximumWordCount;

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

    // ...
}