如何将 jQuery Validation 插件与元数据、jQuery Forms 和 xVal 一起使用?

发布于 2024-08-16 11:11:12 字数 1987 浏览 1 评论 0原文

我一直在使用 .NET 的 xVal 框架进行一些开发,以链接一些验证规则服务器端的模型以及使用 jQuery 验证插件 以及 < a href="http://jquery.malsup.com/form/" rel="nofollow noreferrer">jQuery 表单插件 用于提交表单。

但是,我在将它们连接在一起时遇到问题。

我试图实现以下目标:

  1. 允许客户端使用通过调用 rules("add", options") 用于 jQuery 验证的插件(这是 xVal 用于获取模型服务器端定义的规则的插件)。< /p>

  2. 如果客户端验证成功,则调用服务器输入表单数据再次执行验证(针对在客户端验证的项目,以及无法在客户端执行的任何其他验证)。< /p>

  3. 让服务器返回一个 JSON 格式的对象,该对象指示可能具有特定字段的任何错误,然后设置字段的错误显示。

    让服务器返回一个 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 表单插件提交表单,同时通过调用 ajax 通过 jQuery 验证插件进行验证?

I've been doing some development using the xVal framework for .NET to link up some of the validation rules for models on the server side along with some client side validation using the jQuery Validation plugin along with the jQuery Form plugin for submitting the form.

However, I'm having problems linking them all together.

I'm trying to achieve following:

  1. Allow the client to perform basic validation using rules defined by calling rules("add", options") plugin for jQuery Validation (this is what xVal uses to get rules defined on the server side on the model).

  2. If the client validation succeeds, make the call to the server to input the form data performing validation again (on items that were validated on the client, as well as any other validation which could not be performed in the client).

  3. Have the server return an object in JSON which indicate any errors which might have specific fields and then set the error display for the fields.

I've set up the metadata for the plugin in the ASP.NET MVC page through a call to xVal in the following way:

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

This translates into the following on the client side:

<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>

The above really just translates into a series of calls to rules("add", options) which the jQuery validator plugin then processes.

However when trying to post this form via jQuery forms, the validation doesn't take place on the form values. The form submits, but the values aren't validated at all.

How can I submit the form using the jQuery Form plugin while being validated by the jQuery Validation plugin through a call to ajax?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温暖的光 2024-08-23 11:11:12

将所有这些放在一起时要注意的最重要事情是一小段文档(这在 xVal 的文档中并不明显,它抽象了对 rules( 的调用) "add", options) 在调用 xVal.AttachValidator) 中用于 rules("add", options) (强调我的):

添加指定规则并返回
第一个匹配的所有规则
元素。 要求家长
形式已验证,即
$("form").validate() 被调用
首先。

当 jQuery Form 插件发挥作用,并且您想通过 AJAX 提交表单时,这一点尤其重要,因为您必须在调用 submitHandler 时设置 submitHandler 选项。 a href="http://docs.jquery.com/Plugins/Validation/validate#options" rel="nofollow">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( “添加”,选项)

如果不这样做,则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 类似于标准化视图模型 shell,其中您将特定于响应的内容包装在一个更标准化的部分中,该部分公开了同质调用中所需的信息,如下所示

{
    // 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."
        }
    }
}

鉴于此, options< 的 success 字段/code> 参数 传递给 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)。

如果未定义,则它将获取地图并将其传递给调用 validate(options) 返回的验证器上的 showErrors,使用定位设置错误消息以及通过调用 validate(options) 指定的样式。

The most important thing to look out for when putting all of this together is the little piece of documentation (which isn't really apparent in the documentation for xVal, which abstracts the call to rules("add", options) in the call to xVal.AttachValidator) for rules("add", options) (emphasis mine):

Adds the specified rules and returns
all rules for the first matched
element. Requires that the parent
form is validated, that is,
$("form").validate() is called
first.

This is especially important when the jQuery Form plugin comes into play, and you want to submit the form via AJAX, as you have to set up a submitHandler option in the call to validate(options), like so:

<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>

Because of the documentation quoted above regarding calls to rules("add", options), the call to validate(options) must come before the calls to rules("add", options).

If they do not, then the submitHandler is ignored, never called.

In the end, this means that your client side code has to look like this when putting it all together:

<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") %>

Finally, with all of this wired up, the last thing to do is what to do when the server-side method returns.

You'll want the JSON that's returned from these calls to be something like a standardized viewmodel shell where you have the response-specific content wrapped in a more standardized piece that exposes the information you need across homogeneous calls, something like this:

{
    // 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
}

For the errors on the server, return the same as above, but with a location which has the URL which the user should be redirected to on success (or null if it was not successful) and a map which can be passed directly to the showErrors(errors) method if there are errors on the fields:

{
    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."
        }
    }
}

Given that, the success field of the options parameter passed to ajaxSubmit should be clear:

// 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);
}

All it does is check to see if the newLocation property is defined. If it is defined, then it redirects the current document to the location (which typically would be the url of the newly saved resource).

If it is not defined, then it takes the map and passes it to showErrors on the validator returned by a call to validate(options), setting the error messages using the positioning and style specified by the call to validate(options).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文