gpt4 book ai didi

validation - 在ASP.NET MVC 3中,AllowEmptyString = true的RequiredAttribute

转载 作者:行者123 更新时间:2023-12-03 08:12:17 24 4
gpt4 key购买 nike

如果我的 View 模型中有[Required(AllowEmptyStrings = true)]声明,则始终在空输入上触发验证。我发现the article可以解释为什么会发生。您知道是否有可用的修复程序吗?如果没有,您将如何处理?

最佳答案

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

有以下三个步骤可解决此问题:

  • 创建一个定制属性适配器,该适配器添加验证参数
  • 将适配器注册为适配器工厂
  • 覆盖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()调用完成的,添加了我们的自定义逻辑,然后调用原始函数-您可以了解更多关于 here这种方法的信息。如果您在整个站点中都使用此功能,则可能在_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>

    关于validation - 在ASP.NET MVC 3中,AllowEmptyString = true的RequiredAttribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6437150/

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