【问题标题】:Custom Validation Attribute With Multiple Parameters具有多个参数的自定义验证属性
【发布时间】:2014-11-10 19:32:22
【问题描述】:

我正在尝试构建一个自定义 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() 仅允许单个参数,即被验证对象的值,因此我不能以这种方式覆盖该方法。

关于如何在仍然使用简单剃须刀格式的同时完成此任务的任何想法:

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

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

【问题讨论】:

    标签: c# asp.net-mvc validation razor


    【解决方案1】:

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

    public class WordCountValidator : ValidationAttribute
    {
        readonly int _maximumWordCount;
    
        public WordCountValidator(int words)
        {
            _maximumWordCount = words;
        }
    
        // ...
    }
    

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

    【讨论】:

    • 效果很好!按照您的演示设置构造函数后,我可以简单地添加新的自定义验证器作为字段的注释:[WordCountValidator(150, ErrorMessage = "Over the allowed word limit")]
    • 很高兴听到 :-) 我想有时最好的解决方案就是简单的解决方案!
    猜你喜欢
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 2019-07-10
    • 2020-05-20
    • 2017-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多