3

このサイトは、MVC と DataAnnotations を理解するのに非常に役立ちました。では、質問に移ります。

まず、いくつかの事実: 私は MVC2 と .NET 4.0 フレームワークを使用しています。現在、MVC3 への更新は私にとって選択肢ではありません (これは、私が遭遇した問題の半分に対する最も一般的な答えですが、ここでは実際には問題にならないかもしれません)。

文字列がデータベースの結果セットに既に存在するかどうかを確認するために、完全に機能するカスタム属性を作成しました。クライアント側のメタデータを出力するために、一致するカスタム バリデータと JavaScript も作成しましたが、これも機能します。

私が解決したいのは、バリデータではなくjquery/javascriptを介してクライアントが使用しているエラーメッセージをオーバーライドする方法です。入力フィールドが無効な場合、クライアント側のエラー メッセージに入力フィールドの値を含めたいのですが、これはバリデータでは実行できません。したがって、いくつかのコード:

バリデーター:

public class UniqueStringValidator : DataAnnotationsModelValidator<UniqueStringAttribute>
    {
        public UniqueStringValidator(ModelMetadata metadata, ControllerContext controllerContext,
                                    UniqueStringAttribute attribute)
            : base(metadata, controllerContext, attribute)
        {

        }

        public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
        {
            //declare the services we'll need

            var rule = new ModelClientValidationRule
            {
                ValidationType = "uniquestring",
                ErrorMessage = "The string is not unique.", //I want to override this on the client, but NOT HERE
            };

            //This is how I pull additional attributes from the viewmodel in MVC2 (wish I was on MVC3)
            //"c" represents the current record we're editing, if we're editing
            if (HttpContext.Current.Request.QueryString["c"] != null)
            {
                int id = Convert.ToInt32(HttpContext.Current.Request["c"]);
                string[] stringNames = //call a service and add some query to remove the current record from the results
                    //and return only the column of strings we're interested in

                rule.ValidationParameters.Add("stringlist", stringNames);
            }
            else
            //If we're here, we're not editing an existing record
            {
                string[] stringNames = //call a service and query only the column of interest
                rule.ValidationParameters.Add("stringlist", stringNames);
            }

            return new[] { rule };
        }
    }

これが私のJavaScriptバリデーターです:

    jQuery.validator.addMethod("uniquestring", function (value, element, params) {

    var stringNames = params.stringlist;

    for (var i = 0; i < stringNames .length; i++) {
        if (value == stringNames [i]) {
            //I want to override the error message here so I can include value
            return false;
        }
    }

    return true;
});

私はこれを少し再訪し、何が起こっているのかを本当に理解するためにさらにいくつかのことを試みました. エラーメッセージはページの下部にあるメタデータに設定されており、JavaScript 関数で実行できるのは、検証が成功するか失敗するかを判断することだけです。jqueryを使用して関数の最後にエラーメッセージを追加したり、エラーメッセージ要素をjavascriptのテキストに設定しようとしても、違いがないように見えたり、スクリプトが壊れたりすることはありません(後者のアプローチは「機能する」と思われますが、メタデータによってすぐに上書きされます)。

助言がありますか?

4

1 に答える 1

1

Microsoft の控えめな検証を使用していると仮定すると、エラー メッセージは実際に設定されており、バリデーターで提供しようとしているメッセージを上書きします。jquery バリデーターの作成時にオプションで何も指定されていない場合、(addMethod を介して) バリデーターで指定したメッセージがデフォルトのメッセージになります。

目立たない検証のために、エラーメッセージは検証中の要素の属性として含まれています(私はMVC2を持っていませんが、これは3と4に当てはまります)

ただし、このメッセージは手動でオーバーライドできます。

フォームが次のようになっていると仮定します。

<form action="/controller/action" id="myForm" method="post">        
<input data-val="true" data-val-uniquestring="The string is not unique" type="text" name="foo" id="foo"/>
    <div data-valmsg-for="foo"></div>
    <button type="submit">Ok</button>
</form>

要素の属性でエラー メッセージが指定されていることがわかります。これは、バリデータのセットアップ時に指定したデフォルトのエラー メッセージを上書きします。

このメッセージのすべてのインスタンスを変更するには、次のようにします。

function myCustomMessage(ruleParams, element) {
    return $(element).val() + " is not a unique value";
}

// This snippet must come after the jquery.validate.unobtrusive.js file
$(function () {
    var settings = $("#myForm").validate().settings;

    for (var p in settings.messages) {
        if (typeof settings.messages[p]["uniquestring"] !== "undefined") {
            settings.messages[p]["uniquestring"] = myCustomMessage;
        }
    }

});
于 2013-11-18T04:40:46.560 に答える