【问题标题】:Add custom multiple validations with Parsley使用 Parsley 添加自定义多重验证
【发布时间】:2014-11-20 22:12:59
【问题描述】:

是否可以使用 Parsley 添加自定义多重验证(即依赖多个输入的单个验证)?

我有时想验证<form> 或整个部分,并在该级别而不是<input> 级别提供错误。

例如,想象一个带有<table> 的表单,它允许用户输入颜色和大小的不同组合。假设我想验证没有重复的组合。最佳方法是验证每行的行并在其上方查找重复的行。如果发现重复行,这些整行都是无效的,没有任何单独的输入实际上是无效的。此外,任何字段的更改都可能使该行或其他行无效。

如果我尝试将 "tr.combination" 添加到 inputs 选项,则不会将 <table> 添加到 fields。看起来选项没有传递给构造函数,所以它不返回 ParsleyField 而是返回一个通用的 Parsley 对象。

我离构造ParsleyFieldMultiple 更远了,因为选择器是硬编码的,而且代码高度依赖于checkbox/radio

【问题讨论】:

  • 另一个例子是一个简单的表单,让用户选择以英寸为单位的尺寸。第一个select选择整数值,第二个select选择小数值(即0.125或1/8);目标是验证这两个字段的总和与其他两个英寸输入字段的总和。

标签: validation parsley.js


【解决方案1】:

Parsley 本身无法完成您想要完成的任务。考虑到这似乎是一个非常具体的情况,您可能需要以下解决方案:

  1. 不要创建自定义验证器,而是使用 Parsley events 来执行验证
  2. 根据是否存在重复组合,调整ParsleyForm.validationResult

这不是最优雅的解决方案,但我认为它是最简单的解决方案。其实我不认为你可以找到一个优雅的解决这个问题。

您可以在working jsfiddle 进行测试。

// bind event after form validation
$.listen('parsley:form:validated', function(ParsleyForm) {
    // We only do this for specific forms
    if (ParsleyForm.$element.attr('id') == 'myForm') {
        var combinations = [];

        // foreach tr
        ParsleyForm.$element.find('tr').each(function() {
            var tr = $(this);

            // if there are any inputs
            if (tr.find('input').length > 0) {
                // Add a new combination based on tr's inputs
                combinations.push(tr.find('input:first').val() + '|' + tr.find('input:last').val());
            }
        });

        // sort array
        combinations = combinations.sort();

        // check if there are duplicate combinations
        for (var i = 0; i < combinations.length - 1; i++) {
            // if two combinations are equal, show message
            // and force validation result to false
            if (combinations[i + 1] == combinations[i]) {
                ParsleyForm.validationResult = false;

                $("#form-message-holder")
                    .html('There are some errors with your form')
                    .css('display', 'block');
                return false;
            }
        }

        // otherwise, validation result is true and hide the error message
        ParsleyForm.validationResult = true;
        $("#form-message-holder")
            .html('')
            .css('display', 'none');
    }
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多