我一直在使用 xval .NET的框架链接服务器侧模型的某些验证规则,并使用某些客户端验证 jQuery验证插件 随着 jQuery表单插件 提交表格。

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

我正在尝试实现以下内容:

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

有帮助吗?

解决方案

最重要的 将所有这些放在一起时要注意的事情是一个小文档(在XVal的文档中并不明显,它将调用呼叫提取 rules("add", options) 在电话中 xVal.AttachValidator) 为了 rules("add", options) (强调我的):

添加指定的规则并返回第一个匹配元素的所有规则。 要求对父母表格进行验证,即$(“表单”)。validate()首先称为。

当jQuery表单插件发挥作用时,这一点尤其重要,并且您想通过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).

如果他们不这样做,那么subsithandler就会被忽略,从不打电话。

最后,这意味着您的客户端代码在将所有内容放在一起时必须看起来像这样:

<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 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的位置 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