gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 22:02:30 26 4
gpt4 key购买 nike

我正在尝试构建自定义 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;
}
}

但是,这不起作用,因为 IsValid() 只允许一个参数,即被验证对象的值,所以我不能以这种方式覆盖该方法。

关于如何在仍然使用简单的 Razor 格式的同时完成此操作的任何想法:

        [ViewModel]
[DisplayName("Essay")]
[WordCount(ErrorMessage = "You are over the word limit."), Words = 150]
public string DirectorEmail { get; set; }

[View]
@Html.ValidationMessageFor(model => model.Essay)

最佳答案

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

public class WordCountValidator : ValidationAttribute
{
readonly int _maximumWordCount;

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

// ...
}

这样,当您调用 IsValid() 时,最大字数可供您用于验证目的。这是否有意义,或者像我说的那样,我是否遗漏了什么?

关于c# - 具有多个参数的自定义验证属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26851535/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com