21

私は.NET用のxValフレームワークを使用していくつかの開発を行っており、サーバー側のモデルの検証ルールの一部と、フォームを送信するためのjQuery FormプラグインとともにjQuery Validationプラグインを使用したクライアント側の検証をリンクしています。

ただし、それらをすべてリンクするのに問題があります。

私は以下を達成しようとしています:

  1. jQuery Validation のプラグインを呼び出すことによって定義されたルールを使用して、クライアントが基本的な検証を実行できるようにしますrules("add", options")(これは、xVal がモデルのサーバー側で定義されたルールを取得するために使用するものです)。

  2. クライアントの検証が成功した場合は、サーバーを呼び出してフォーム データを入力し、検証を再度実行します (クライアントで検証された項目、およびクライアントで実行できなかったその他の検証)。

  3. 特定のフィールドを持つ可能性のあるエラーを示す JSON のオブジェクトをサーバーに返させ、フィールドのエラー表示を設定します。

次の方法で xVal を呼び出して、ASP.NET MVC ページでプラグインのメタデータを設定しました。

<%= Html.ClientSideValidation<Model>("model") %>

これは、クライアント側で次のように変換されます。

<script type="text/javascript">
xVal.AttachValidator("model", 
{
    "Fields": 
    [ 
        {
            "FieldName":"title",
            "FieldRules": 
            [
                {
                    "RuleName":"Required",
                    "RuleParameters":{}
                },
                {
                    "RuleName":"StringLength",
                    "RuleParameters":
                    {
                        "MaxLength":"250"
                    }
                }
            ]
        },
        {
            "FieldName":"body",
            "FieldRules":
            [
                {
                    "RuleName":"Required",
                    "RuleParameters":{}
                }
            ]
        }
    ]
}, {})
</script>

rules("add", options)上記は実際には、jQuery バリデータ プラグインが処理する一連の呼び出しに変換されます。

ただし、このフォームを jQuery フォーム経由で投稿しようとすると、フォームの値に対して検証が行われません。フォームは送信されますが、値はまったく検証されません。

への呼び出しを通じて jQuery Validation プラグインによって検証されている間に、jQuery Form プラグインを使用してフォームを送信するにはどうすればよいajaxですか?

4

1 に答える 1

5

これらすべてをまとめるときに注意すべき最も重要なrules("add", options)ことは、ドキュメントの小さな部分です (これは、への呼び出しでへの呼び出しを抽象化する xVal のドキュメントでは実際には明らかではありませんxVal.AttachValidator) for rules("add", options)(私のものを強調):

指定されたルールを追加し、最初に一致した要素のすべてのルールを返します。 親フォームが検証される必要があります。つまり、最初に $("form").validate() が呼び出されます。

submitHandlerこれは、jQuery フォーム プラグインが有効になり、AJAX 経由でフォームを送信する場合に特に重要です。次のように、への呼び出しでオプションを設定する必要がvalidate(options)あるためです。

<script type="text/javascript">
    $(document).ready(function() {
        // Initialize the form.  Store the validator.
        var validator = $("form").validate({

            // Called when the form is valid.
            submitHandler: function(form) {

                // Submit the form via ajax.
                $(form).ajaxSubmit({

                    // The return data type is json.
                    dataType: "json",

                    // The callback on a successful form
                    // submission.
                    success: function(data, statusText) {

                        // If the new location is not null, then
                        // redirect to that location.
                        if (data.data.newLocation) {
                            // Go to the new location.
                            document.location.href = data.data.newLocation;

                            // Get out.
                            return;
                        }

                        // There are errors, pass them to the validator
                        // for display.
                        validator.showErrors(data.data.errors);
                    }
                });
            }
        });
    });
</script>

への呼び出しに関する上記のドキュメントのため、 へrules("add", options)呼び出しvalidate(options)は への呼び出しの前に来る必要がありますrules("add", options)

そうでない場合、submitHandler は無視され、呼び出されることはありません。

最終的に、これは、クライアント側のコードをすべてまとめると、次のようになる必要があることを意味します。

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.validate.min.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<!-- Note this is only needed if using xVal. -->
<script type="text/javascript" src="xVal.jquery.validate.js"></script>
<!-- The call to validate the form must come first. -->
<script type="text/javascript">
    $(document).ready(function() {
        // Initialize the form.
        $("form").validate({

            // Called when the form is valid.
            submitHandler: function(form) {

                // Submit the form via ajax.
                $(form).ajaxSubmit({

                    // The return data type is json.
                    dataType: "json",

                    // The callback.
                    success: function(data, statusText) {

                        // Alert the users to the message.
                        window.alert(statusText);
                    }
                });
            }
        });
    });
</script>

<!-- Now make the calls to rules("add", options), AFTER the call to -->
<!-- validate (options). It's separated into another block for      -->
<!-- emphasis, but could be done in the block above.                -->
<script type="text/javascript">
    // Make calls to rules("add", options).
</script>

<!-- Or, if you are using xVal, make the following call in the ASP.NET -->
<!-- page but again, note it must come AFTER the call to               -->
<!-- validate(options).                                                -->
<%= Html.ClientSideValidation<Model>("model") %>

最後に、これらすべてを接続したら、最後に行うことは、サーバー側のメソッドが返されたときに何をするかです。

これらの呼び出しから返される JSON は、標準化されたビューモデル シェルのようなものにする必要があります。このシェルでは、応答固有のコンテンツが、同種の呼び出し全体で必要な情報を公開する、より標準化された部分にラップされています。次のようなものです。

{
    // An integer, non-zero indicates faulure, with predefined ranges
    // for standard errors across all operations, with other ranges for custom
    // errors which are operation-specific.  Examples of shared errors
    // are not authenticated, not authorized, etc, etc.
    resultCode: 0,

    // A string, which is to be displayed to the user (usually in the
    // form of a jQuery dialog, usually used for the common ranges of
    // errors defined above.
    message: null,

    // An object with operation-specific results.
    data: null
}

サーバー上のエラーの場合は、上記と同じものを返しますが、成功時にユーザーがリダイレクトされる URL (成功しなかった場合は null) と、showErrors(errors)メソッドに直接渡すことができるマップを含む場所を返します。フィールドにエラーがある場合:

{
    resultCode: 0,

    message: null,

    data:
    {
        // Returned as a string.  If not null, then this is the url
        // that the client should be redirected to, as the server-side
        // operation was successful.
        newLocation: null,

        // If not-null, then this is a map which has the names of the
        // fields with the errors, along with the errors for the fields.
        errors:
        {
            "model.title": "The title already exists in the system.",
            "model.body": "The body cannot have malicious HTML code in it."
        }
    }
}

それを考えると、渡されるパラメーターのsuccessフィールドはoptionsajaxSubmit明確である必要があります。

// The callback on a successful form
// submission.
success: function(data, statusText) {

    // If the new location is not null, then
    // redirect to that location.
    if (data.data.newLocation) {
        // Go to the new location.
        document.location.href = data.data.newLocation;

        // Get out.
        return;
    }

    // There are errors, pass them to the validator
    // for display.
    validator.showErrors(data.data.errors);
}

newLocationプロパティが定義されているかどうかを確認するだけです。定義されている場合は、現在のドキュメントをその場所 (通常は新しく保存されたリソースの URL) にリダイレクトします。

定義されていない場合は、マップをshowErrors取得し、 への呼び出しによって返されたバリデータに渡し、 へvalidate(options)の呼び出しによって指定された位置とスタイルを使用してエラー メッセージを設定しますvalidate(options)

于 2012-10-10T12:53:44.493 に答える