كيفية استخدام المكون الإضافي للتحقق من صحة JQuery مع بيانات التعريف وأشكال jQuery و XVAL معًا؟

StackOverflow https://stackoverflow.com/questions/1996125

سؤال

لقد كنت أقوم ببعض التطوير باستخدام xval إطار عمل .NET لربط بعض قواعد التحقق من صحة النماذج على جانب الخادم مع بعض التحقق من صحة جانب العميل باستخدام المكوّن الإضافي للتحقق من صحة jQuery جنبا إلى جنب مع jQuery Form Plugin لتقديم النموذج.

ومع ذلك ، أواجه مشاكل في ربطهم جميعًا معًا.

أحاول تحقيق المتابعة:

  1. السماح للعميل بإجراء التحقق الأساسي باستخدام القواعد المحددة عن طريق الاتصال rules("add", options") البرنامج المساعد للتحقق من صحة jQuery (هذا ما يستخدمه XVAL للحصول على قواعد محددة على جانب الخادم على النموذج).

  2. إذا نجحت التحقق من صحة العميل ، اجعل المكالمة إلى الخادم لإدخال بيانات النموذج التي تؤدي إلى صحة مرة أخرى (على العناصر التي تم التحقق من صحتها على العميل ، وكذلك أي التحقق الآخر الذي لا يمكن تنفيذه في العميل).

  3. اطلب من الخادم إرجاع كائن في JSON يشير إلى أي أخطاء قد تحتوي على حقول محددة ثم ضبط عرض الخطأ للحقول.

لقد قمت بإعداد البيانات الوصفية للمكون الإضافي في صفحة ASP.NET MVC من خلال مكالمة إلى XVAL بالطريقة التالية:

<%= 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 Form أثناء التحقق من صحة المكون الإضافي لـ jQuery من خلال مكالمة إلى ajax?

هل كانت مفيدة؟

المحلول

ال الأهم الشيء الذي يجب البحث عنه عند تجميع كل هذا معًا هو الوثائق الصغيرة (التي ليست واضحة حقًا في الوثائق الخاصة بـ XVAL ، والتي تملأ الدعوة إلى rules("add", options) في الدعوة إلى xVal.AttachValidator) إلى عن على rules("add", options) (التأكيد لي):

يضيف القواعد المحددة ويعيد جميع القواعد للعنصر المتطابق الأول. يتطلب التحقق من صحة النموذج الأصل ، أي ، $ ("form"). تم استدعاء التحقق () أولاً.

هذا مهم بشكل خاص عندما يتم تشغيل المكون الإضافي لـ jQuery Form ، وتريد إرسال النموذج عبر Ajax ، حيث يتعين عليك إعداد أ submitHandler الخيار في المكالمة إلى 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 التي يتم إرجاعها من هذه المكالمات تشبه قذيفة ViewModel موحدة حيث لديك محتوى خاص بالاستجابة ملفوف في قطعة أكثر موحدة تكشف المعلومات التي تحتاجها عبر مكالمات متجانسة ، شيء مثل هذا:

{
    // 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 مجال options معامل مرت ل ajaxSubmit يجب أن يكون واضحا:

// 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).

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top