【问题标题】:Shared validation error message for more than one field多个字段的共享验证错误消息
【发布时间】:2014-03-20 11:47:59
【问题描述】:

在一个 ASP.NET MVC 项目中,我试图根据正则表达式验证几个字段。但是,如果其中任何一个失败,我希望只显示一条验证消息(并突出显示失败的消息)。

我可以对此进行自定义验证,并用其他工作的 id 注释其中一个,尽管只突出显示用该属性装饰的那个。但在我看来,这有点矫枉过正,因为我只想将消息减少到一个。

在同一个表单中,我将尝试对两个复选框执行相同的操作,都必须选中。

据我所知,如果我使用摘要来放置通用消息,则无法判断复选框或字段是否失败。

有没有一种简单的方法来实现这一点?

【问题讨论】:

    标签: c# asp.net-mvc validation


    【解决方案1】:

    您可以编写针对整个视图模型类的自定义验证。当我想检查是否设置了至少一个属性时,我写了以下内容。您可以看到这是针对类本身的,因此应该给您一条消息。

    /// <summary>
    /// A configurable class wide attribute that is used to determine if at least one property of a class has received a value.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class SingleValueConfigurableAttribute : ValidationAttribute, IClientValidatable
    {
        public SingleValueConfigurableAttribute(string errorKey)
        { ErrorMessage = Properties.Settings.Default[errorKey].ToString(); }
    
        public override bool IsValid(object value)
        {
            var typeInfo = value.GetType();
            var propertyInfo = typeInfo.GetProperties();
    
            return propertyInfo.Any(property => null != property.GetValue(value, null));
        }
    
        public override string FormatErrorMessage(string name)
        {
            return ErrorMessage;
        }
    
        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        {
            yield return new ModelClientValidationRule
            {
                ErrorMessage = String.IsNullOrEmpty(ErrorMessage) ? FormatErrorMessage(metadata.DisplayName) : ErrorMessage,
                ValidationType = "enforcetrue"
            };
        }
    }
    

    【讨论】:

    • 谢谢@DavidHirst 我正在尝试将它与 jquery 验证连接起来,并将更新
    猜你喜欢
    • 2019-04-28
    • 2017-12-24
    • 1970-01-01
    • 2011-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-03
    • 2021-08-29
    相关资源
    最近更新 更多