21

如果[Required(AllowEmptyStrings = true)]我的视图模型中有声明,则始终在空输入上触发验证。我找到了解释为什么会发生的文章。你知道是否有可用的修复程序吗?如果没有,你如何处理它?

4

2 回答 2

23

注意:我假设您有 AllowEmptyStrings = true 因为您还在 Web 场景之外使用您的视图模型;否则,在 Web 场景中拥有允许空字符串的必需属性似乎没有多大意义。

有以下三个步骤来处理:

  1. 创建一个添加该验证参数的自定义属性适配器
  2. 将您的适配器注册为适配器工厂
  3. 覆盖 jQuery Validation 函数以在该属性存在时允许空字符串

第 1 步:自定义属性适配器

我修改了RequiredAttributeAdapter 以添加该逻辑:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace CustomAttributes
{
    /// <summary>Provides an adapter for the <see cref="T:System.Runtime.CompilerServices.RequiredAttributeAttribute" /> attribute.</summary>
    public class RequiredAttributeAdapter : DataAnnotationsModelValidator<RequiredAttribute>
    {
        /// <summary>Initializes a new instance of the <see cref="T:System.Runtime.CompilerServices.RequiredAttributeAttribute" /> class.</summary>
        /// <param name="metadata">The model metadata.</param>
        /// <param name="context">The controller context.</param>
        /// <param name="attribute">The required attribute.</param>
        public RequiredAttributeAdapter(ModelMetadata metadata, ControllerContext context, RequiredAttribute attribute)
            : base(metadata, context, attribute)
        {
        }
        /// <summary>Gets a list of required-value client validation rules.</summary>
        /// <returns>A list of required-value client validation rules.</returns>
        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            var rule = new ModelClientValidationRequiredRule(base.ErrorMessage);
            if (base.Attribute.AllowEmptyStrings)
            {
                //setting "true" rather than bool true which is serialized as "True"
                rule.ValidationParameters["allowempty"] = "true";
            }

            return new ModelClientValidationRequiredRule[] { rule };
        }
    }
}

步骤 2. 在您的 global.asax / Application_Start() 中注册

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        DataAnnotationsModelValidatorProvider.RegisterAdapterFactory(typeof(RequiredAttribute),
          (metadata, controllerContext, attribute) => new CustomAttributes.RequiredAttributeAdapter(metadata,
            controllerContext, (RequiredAttribute)attribute)); 

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);
    }

步骤 3. 覆盖 jQuery“必需”验证函数

这是使用 jQuery.validator.addMethod() 调用完成的,添加我们的自定义逻辑,然后调用原始函数 - 您可以在此处阅读有关此方法的更多信息。如果您在整个站点中使用它,可能在您的 _Layout.cshtml 引用的脚本文件中。这是一个示例脚本块,您可以放入页面进行测试:

<script>
jQuery.validator.methods.oldRequired = jQuery.validator.methods.required;

jQuery.validator.addMethod("required", function (value, element, param) {
    if ($(element).attr('data-val-required-allowempty') == 'true') {
        return true;
    }
    return jQuery.validator.methods.oldRequired.call(this, value, element, param);
},
jQuery.validator.messages.required // use default message
);
</script>
于 2011-06-27T20:50:30.247 回答
15

我没有使用“必需”属性来装饰值,而是使用以下内容。我发现这是解决这个问题的最简单的方法。

[DisplayFormat(ConvertEmptyStringToNull=false)]

于 2013-09-09T07:02:42.107 回答