21

我一直在使用 .NET 的xVal框架进行一些开发,以链接服务器端模型的一些验证规则以及使用jQuery Validation 插件和用于提交表单的jQuery Form 插件的一些客户端验证。

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

我正在努力实现以下目标:

  1. 允许客户端使用通过调用rules("add", options")jQuery Validation 插件定义的规则执行基本验证(这是 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 Form 插件提交表单,同时通过调用 jQuery Validation 插件进行验证ajax

4

1 回答 1

5

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

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

submitHandler当 jQuery Form 插件开始发挥作用时,这一点尤其重要,并且您想通过 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 回答