[英]Custom Validation Attribute With Multiple Parameters
I am trying to build a custom ValidationAttribute to validate the number of words for a given string: 我试图建立一个自定义的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;
}
}
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. 但是,这不起作用,因为IsValid()仅允许使用单个参数,该参数的值已通过验证,因此我无法以这种方式覆盖该方法。
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? 我可能会遗漏一些显而易见的东西-这在我身上经常发生-但您是否无法将最大字数保存为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. 这样,当您调用
IsValid()
,最大字数可用于验证目的。 Does this make sense, or like I said, am I missing something? 这是否有意义,或者像我说的那样,我是否缺少某些东西?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.