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

时间:2010-01-03 20:09:29

标签: javascript jquery jquery-validate xval jquery-forms-plugin

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

然而,我在将它们连接在一起时遇到了问题。

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

  1. 允许客户端使用通过调用jQuery Validation的rules("add", options")插件定义的规则来执行基本验证(这是xVal用于获取模型上服务器端定义的规则的内容)。

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

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

  4. 我通过以下方式调用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 Validation插件验证,使用jQuery Form插件提交表单?

1 个答案:

答案 0 :(得分:5)

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

  

添加指定的规则并返回   第一个匹配的所有规则   元件。 要求父母   表格经过验证,即   调用$(“form”)。validate()   第一

当jQuery Form插件发挥作用,并且您想通过AJAX提交表单时,这一点尤其重要,因为您必须在validate(options)的调用中设置xVal.AttachValidator选项,就像这样:

rules("add", options)

由于上面引用的有关submitHandler的来电的文档,对<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) 之前发出。

如果没有,则忽略submitHandler,从不调用。

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

validate(options)

最后,在所有这些连线的情况下,最后要做的是在服务器端方法返回时该怎么做。

您希望从这些调用返回的JSON类似于标准化的viewmodel shell,其中您将特定于响应的内容包装在一个更标准化的部分中,该部分公开了您在同类调用中所需的信息,如下所示:

rules("add", options)

对于服务器上的错误,返回与上面相同的内容,但是其位置具有成功时用户应重定向到的URL(如果不成功则返回null)和可以直接传递的映射如果字段中存在错误,请使用showErrors(errors)方法:

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

鉴于此,传递给success field of the options parameterajaxSubmit应该是明确的:

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

它只是检查是否定义了{ 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." } } } 属性。如果已定义,则将当前文档重定向到该位置(通常是新保存资源的URL)。

如果没有定义,那么它将获取地图并将其传递给// 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上的showErrors,使用调用指定的定位和样式设置错误消息到validate(options)