在具有多个部分和未知输入字段的表单上触发验证 [英] Trigger validation on form with multiple sections and unknown input fields

查看:56
本文介绍了在具有多个部分和未知输入字段的表单上触发验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证一个复杂的表格,用复杂的方式表示该表格只是一个表格,但已分为四个部分,我制作了一个简单的向导来显示它们.我正在使用 jQuery验证,但是它不能按我的意愿工作,对此也有一些疑问.基于此示例(第二种形式),我编写了如下代码:

I'm trying to validate a complex form and by complex I mean that form is just one but it has been split in four sections and I made a simple wizard to show them. I'm using jQuery Validation but it's not working as I want and also have some doubts about it. Based on this example (second form) I made my code as follow:

$("#product_create").validate({
    rules: {
        product_name: {
            required: true,
            minlength: 10,
            maxlength: 50
        },
        product_price: {
            required: true,
            number: true,
            minlength: 2
        },
        product_quantity: {
            required: true,
            digits: true,
            minlength: 1
        }
    },
    messages: {
        product_name: {
            required: "El nombre del producto no se puede dejar vacío",
            minlength: "El nombre del producto no puede tener menos de 10 carácteres",
            maxlength: "El nombre del producto no puede tener más de 50 carácteres"
        },
        product_price: {
            required: "Debes introducir un precio",
            number: "El precio debe ser un número decimal o no"
        },
        product_quantity: {
            required: "Debes introducir una cantidad",
            number: "La cantidad debe ser un número"
        }
    }
});

如果我理解的很好,那么在keyup上的事件字段应该有效,而不会出现错误,因为不会出现错误.因此,与此有关的第一个问题是:为什么它不通过验证?我的解决方案出了什么问题?第二个是仅在可见的情况下如何验证product_priceproduct_quantity的方法?

If I understand good then on keyup event fields should validate and they are not since errors doesn't come up. So first problem regarding this is: why it doesn't validate? What's wrong in my solution? Second one is how I validate product_price and product_quantity only if they are visible?

现在,对于同一主题,我还有另一个疑问,我即时创建了几个字段,是的,我每次都知道它们的ID,在这种情况下,我如何将规则应用于这些字段?

Now regarding this same topic I have another doubt, I create several fields on the fly and yes I know theirs ID each time, in this case how I apply rules to those fields?

更新

我弄清楚了keyup的问题在哪里,验证是通过输入名称而不是输入ID进行的,所以我完成了这一部分.

I figure out where the problem with keyup was, validation is made by input name and not input id's as I tough, so this part is done.

第二个问题仍然悬而未决.例如,我可以生成三个名称为variation[pprice][]的字段,但可以是五个或更多字段,如何将这些字段添加到规则和验证部分?我可以只添加variation[pprice][]的规则吗,无论表单中有多少个具有相同名称的元素,它都可以验证?

The second problem still pending. For example I can generate three fields with name variation[pprice][] and the fly but can be five or more or whatever, how I add those fields to rules and validation part? Can I just add the rule for variation[pprice][] and it will validates no matter how many elements with the same name are in the form?

即使它们是可见的,也要等待验证字段的一部分

Also is pending the part of validate fields just if they are visible

更新2

由于variation[pprice][]是项目的数组,我可以使用$.each为其移动并分配规则吗?

Since variation[pprice][] is a array of items, can I use $.each to move for them and assign rules?

更新3

按照@Sparky的建议,我将代码更改为此:

Following recommendations by @Sparky I change my code to this:

$('#variations_holder input.pprice').each(function() {
    $(this).rules('add', {
        required: true,
        number: true,
        messages: {
            required: "Debes introducir un precio de la variación",
            number: "El precio de la variación debe ser un valor numérico o decimal"
        }
    });
});

但是在Firebug中,我收到此错误:

But in Firebug I get this error:

TypeError:e.validator.methods [o]未定义

TypeError: e.validator.methods[o] is undefined

哪个会阻止脚本执行代码,在这种情况下我会错过什么?

Which prevent code execution for the script, what I miss in this case?

更新4

假设我不能使用多种形式,所以我只有一种具有很多部分的形式(使用section标记),并且我要在每种形式之间移动.我试图以相同的形式调用validate(),但是两次,由于字段通过,在step5处的验证不起作用.这是我正在使用的代码:

Supposing that I can't use several forms so I only have one form with many sections (using section tag) and I handle to move between each. I'm trying to call validate() in same form but two times and validation at step5 didn't work since fields pass. This is the code I'm using for that:

功能validateWizard(步骤){ var is_valid = true;

function validateWizard(step) { var is_valid = true;

switch (step) {
    case 1:
        if ($("#selected_category").val() === '' || $("#selected_category").val().length === 0) {
            alert("Debes seleccionar una categoría antes de continuar");
            is_valid = false;
        }
        break;
    case 2:
        $("#product_create").validate({
            rules: {
                "product[name]": {
                    required: true,
                    minlength: 10,
                    maxlength: 50
                },
                "product[price]": {
                    required: true,
                    number: true,
                    minlength: 2
                },
                "product[quantity]": {
                    required: true,
                    digits: true,
                    minlength: 1
                },
                "product[description]": {
                    required: true
                }
            },
            messages: {
                "product[name]": {
                    required: "El nombre del producto no se puede dejar vacío",
                    minlength: "El nombre del producto no puede tener menos de 10 carácteres",
                    maxlength: "El nombre del producto no puede tener más de 50 carácteres"
                },
                "product[price]": {
                    required: "Debes introducir un precio",
                    number: "El precio debe ser un valor numérico o decimal"
                },
                "product[quantity]": {
                    required: "Debes introducir una cantidad",
                    number: "La cantidad debe ser un número"
                },
                "product[description]": {
                    required: "Debes introducir una descripción del producto"
                }
            }
        });

        is_valid = $("#product_create").valid();

        if (is_valid) {
            $('#variations_holder input.pprice').each(function() {
                pprice = $.trim(this.value);
                if (!pprice.length) {
                    $(this).focus();
                    $(this).addClass('error');
                    is_valid = false;
                } else if (!/^[1-9]\d*(\.\d+)?$/.test(pprice)) {
                    $(this).addClass('error');
                    is_valid = false;
                }
            });

            // Validate quantity in variation
            $('#variations_holder input.pqty').each(function() {
                pqty = $.trim(this.value);
                if (!pqty.length) {
                    $(this).focus();
                    $(this).addClass('error');
                    is_valid = false;
                } else if (!/^[1-9]\d*$/.test(pqty)) {
                    $(this).addClass('error');
                    is_valid = false;
                }
            });
        }
        break;
    case 3:
        break;
    case 5:
        $("#product_create").validate({
            rules: {
                "stock[sku]": {
                    required: true,
                    minlength: 10,
                    maxlength: 20
                },
                "stock[width]": {
                    required: true,
                    number: true,
                    minlength: 1
                },
                "stock[height]": {
                    required: true,
                    number: true,
                    minlength: 1
                },
                "stock[length]": {
                    required: true
                },
                "stock[weight]": {
                    required: true,
                    number: true,
                    minlength: 1
                },
                "stock[description]": {
                    required: true
                },
                "warranty[description]": {
                    required: true
                },
                "warranty[valid_time]": {
                    required: true,
                    digits: true
                }
            },
            messages: {
                "stock[sku]": {
                    required: "El SKU no se puede dejar vacío",
                    minlength: "El SKU no puede tener menos de 10 carácteres",
                    maxlength: "El SKU no puede tener más de 50 carácteres"
                },
                "stock[width]": {
                    required: "Debes introducir un ancho",
                    number: "El ancho debe ser un número"
                },
                "stock[height]": {
                    required: "Debes introducir una altura",
                    number: "La altura debe ser un número"
                },
                "stock[length]": {
                    required: "Debes introducir una longitud",
                    number: "La longitud debe ser un número"
                },
                "stock[weight]": {
                    required: "Debes introducir un peso",
                    number: "El peso debe ser un número"
                },
                "stock[description]": {
                    required: "Debes introducir una descripción del stock del producto"
                },
                "warranty[description]": {
                    required: "Debes introducir una descripción de la garantía para este producto"
                },
                "warranty[valid_time]": {
                    required: "Debes introducir un período de validez",
                    digits: "El período de validez no es válido"
                },
            }
        });

        is_valid = $("#product_create").valid();
        break;
}

return is_valid;

}

我的问题是,如果表单在step5处无效,为什么会通过?应该失败吗?

my question is why if form is not valid at step5 it pass? Should't fail?

推荐答案

静音OP :

由于variation[pprice][]是一组项目,我可以使用$.each为其移动并分配规则吗?"

"Since variation[pprice][] is a array of items, can I use $.each to move for them and assign rules?"

当jQuery选择器定位多个输入元素时,必须使用.each(). 但是,这并不能解决 jQuery Validate插件要求每个输入元素包含唯一的name属性的事实.这就是插件跟踪元素的方式. (具有相同名称的一组单选元素或复选框元素不是问题,因为当它们进行分组时,它们应该具有相同的名称...该组充当单个数据输入.)

You must use .each() when the jQuery selector targets more than one input element. However, this does not get around the fact that the jQuery Validate plugin requires that each input element contain a unique name attribute. This is how the plugin keeps track of elements. (A group of radio or checkbox elements with the same name is not an issue since, when they're grouped, they're supposed to have the same name... the group acts as a single data input.)

无效,因为存在多个具有相同name ...

$('input[name="something"]').each(function() {
    $(this).rules('add', function() {
        required: true,
        // another rule, etc,
    });
});

只要每个输入元素包含唯一的name ...

This will work as long as each input element contains a unique name...

$('input.class').each(function() {
    $(this).rules('add', function() {
        required: true,
        // another rule, etc,
    });
});

有关定义和应用规则的各种方式,请参见此答案.

See this answer for the various ways rules can be defined and applied.

有多种方法可以处理阶梯式表格.

There are various approaches to stepped forms.

当我创建多步骤表单时,我为每个部分使用一组唯一的<form>标签.然后,我将使用 .valid()方法来测试该部分,然后再进行下一步. (别忘了先初始化插件;在DOM上的所有表单上都调用.validate().)

When I create multi-step forms, I use a unique set of <form> tags for each section. Then I use the .valid() method to test the section before moving to the next. (Don't forget to first initialize the plugin; call .validate(), on all forms on DOM ready.)

然后在最后一节中,我在每种表单上使用.serialize()并将它们连接到要提交的数据查询字符串中.

Then on the last section, I use .serialize() on each form and concatenate them into a data query string to be submitted.

类似这样的事情...

Something like this...

$(document).ready(function() {

    $('#form1').validate({ // initialize form 1
        // rules
    });

    $('#gotoStep2').on('click', function() { // go to step 2
        if ($('#form1').valid()) {
            // code to reveal step 2 and hide step 1
        }
    });

    $('#form2').validate({ // initialize form 2
        // rules
    });

    $('#gotoStep3').on('click', function() { // go to step 3
        if ($('#form2').valid()) {
            // code to reveal step 3 and hide step 2
        }
    });

    $('#form3').validate({ initialize form 3
        // rules,
        submitHandler: function (form) {
           // serialize and join data for all forms
           // ajax submit
           return false;
        }
    });

    // there is no third click handler since the plugin takes care of this 
    // with the built-in submitHandler callback function on the last form.

});

重要的是要记住我上面的click处理程序没有使用type="submit"按钮.这些是常规按钮,它们是form标签的外部type="button".

Important to remember that my click handlers above are not using type="submit" buttons. These are regular buttons, either outside of the form tags or type="button".

仅最后一个表单上的按钮是常规的type="submit"按钮.那是因为我仅在最后一种形式上利用了插件的内置submitHandler回调函数.

Only the button on the very last form is a regular type="submit" button. That is because I am leveraging the plugin's built-in submitHandler callback function on only the very last form.

概念验证"演示: http://jsfiddle.net/N9UpD/

"Proof of Concept" DEMO: http://jsfiddle.net/N9UpD/

另外,请参阅以供参考:

Also, see for reference:

https://stackoverflow.com/a/17975061/594235

这篇关于在具有多个部分和未知输入字段的表单上触发验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆