本文介绍了在 ASP.NET MVC 3 不显眼的验证中,RequiredAttribute 和 AllowEmptyString=true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

If i have [Required(AllowEmptyStrings = true)] declaration in my view model the validation is always triggered on empty inputs. I found the article which explains why it happens. Do you know if there is a fix available? If not, how do you handle it?

推荐答案

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

解决这个问题需要三个步骤:

There are three steps to handle this:

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

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

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

I modified the RequiredAttributeAdapter to add in that logic:

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 引用的脚本文件中.这是一个示例脚本块,您可以放入页面中进行测试:

This is done using the jQuery.validator.addMethod() call, adding our custom logic and then calling the original function - you can read more about this approach here. If you are using this throughout your site, perhaps in a script file referenced from your _Layout.cshtml. Here's a sample script block you can drop in a page to test:

<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>

这篇关于在 ASP.NET MVC 3 不显眼的验证中,RequiredAttribute 和 AllowEmptyString=true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 20:14