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)
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?
上一篇: 我可以将自定义属性仅限于void方法吗?
下一篇: 具有多个参数的自定义验证属性