ASP.NET MVC 3 の控えめな検証で AllowEmptyString=true を指定した RequiredAttribute 質問する

ASP.NET MVC 3 の控えめな検証で AllowEmptyString=true を指定した RequiredAttribute 質問する

ビューモデルに宣言がある場合、[Required(AllowEmptyStrings = true)]空の入力では常に検証が実行されます。記事これがなぜ起こるのかを説明しています。修正方法があるかどうかご存知ですか? ない場合は、どのように対処しますか?

ベストアンサー1

注: Web シナリオ以外でもビュー モデルを使用しているため、AllowEmptyStrings = true が設定されているものと想定しています。それ以外の場合、Web シナリオで空の文字列を許可する Required 属性を設定することにあまり意味がないようです。

これを処理するには、次の 3 つの手順があります。

  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>

おすすめ記事