0

我正在尝试验证一个复杂的表单,而复杂的意思是该表单只是一个,但它已分为四个部分,我制作了一个简单的向导来显示它们。我正在使用jQuery Validation,但它没有按我的意愿工作,并且对此也有一些疑问。基于这个例子(第二种形式)我做了我的代码如下:

$("#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_price并且product_quantity只有当它们可见时?

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

更新

我弄清楚问题出在哪里keyup,验证是通过输入名称而不是输入 id 进行的,因为我很难,所以这部分完成了。

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

也正在等待验证字段的一部分,如果它们是可见的

更新 2

既然variation[pprice][]是一组项目,我可以用它$.each来移动它们并分配规则吗?

更新 3

根据@Sparky 的建议,我将代码更改为:

$('#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 中,我收到此错误:

类型错误:e.validator.methods[o] 未定义

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

更新 4

假设我不能使用多个表单,所以我只有一个包含多个部分(使用section标签)的表单,并且我处理在每个表单之间移动。我试图以相同的形式调用,但由于字段通过validate(),验证失败了两次。step5这是我为此使用的代码:

函数验证向导(步骤){ 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?不应该失败吗?

4

2 回答 2

1

安静的OP

“既然variation[pprice][]是物品数组,我可以$.each用来为它们移动并分配规则吗?”

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

不起作用,因为有多个输入元素具有相同的name......

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

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

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

有关可以定义和应用规则的各种方式,请参阅此答案。


阶梯形式有多种方法。

当我创建多步骤表单时,我<form>为每个部分使用一组唯一的标签。然后我使用.valid()方法测试该部分,然后再转到下一个。 (不要忘记首先初始化插件;.validate()在 DOM 上的所有表单上调用 , 准备就绪。)

然后在最后一部分,我.serialize()在每个表单上使用并将它们连接成要提交的数据查询字符串。

像这样的东西...

$(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"按钮。这些是常规按钮,位于标签之外或.formtype="button"

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

“概念证明”演示:http: //jsfiddle.net/N9UpD/

另外,请参阅以供参考:

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

于 2013-10-09T17:43:54.817 回答
0

Supposed that you set a config rules each time you load a step, then you can keep one config rules for each step.

To remove the validation of the hidden fields, you could create a JavaScript function called each time you changed the visibility's fields, at this function you can set again the config rules or you could remove the link between the config rules and the field elements, only for the hidden fields. I understod that this link is the tag name, to set the tag name you can use this code$('#element').attr('name',null).

于 2013-10-08T20:17:59.137 回答