在 'parsley:field:success' 上使用多个 Parsley Field 实例?

Use more than one Parsley Field instance on 'parsley:field:success'?

我正在尝试在验证了两个特定字段后删除表单上的验证消息。

我可以在一个字段成功验证时执行此操作,但是当多个字段(甚至可能是一组)已被验证时我将如何执行此操作?

以下是我要完成的工作

$.listen('parsley:field:success', function (parsleyField) {
    if ((parsleyField.$element.attr('name') == 'field1')) && ((parsleyField.$element.attr('name') == 'field2')){
        $(".tab-nav-1").removeClass("tab-validation-error")
    }
});

有没有办法在验证一组字段时执行某些操作(即使表单未验证)?

这不起作用,因为 parsleyField 仅与一个字段相关联。也就是说,如果您有一个包含两个(有效)输入的表单,则该函数将为每个输入执行一次。

更新解决方案

正在查看Parsley's events turns out you can use parsley:form:validated which is triggered after the form validation is performed. The use of this event simplifies the solution quite a bit because you can simply check if the inputs are valid. Here's the code you need (jsfiddle available):

$.listen('parsley:form:validated', function (parsleyForm) {
    var isValidField1 = $("input[name=field1]").parsley().isValid(),
        isValidField2 = $("input[name=field2]").parsley().isValid();

    if (isValidField1 && isValidField2) {
        $(".tab-nav-1").removeClass("tab-validation-error");
    } else {
        $(".tab-nav-1").addClass("tab-validation-error");
    }
});

原解

您可以创建一个数组来存储输入字段并在它们变得无效时将其删除。然后,每次执行验证时,只需检查数组中是否存在字段,如果存在,则删除 class。否则,添加 class.

诚然,解决方案并不像人们希望的那样直接。看看下面的代码(jsfiddle available)

// this will store our valid fields
var validFields = [];

$("form").parsley();

// whenever a field is valid
$.listen('parsley:field:success', function (parsleyField) {
    // add this field's name to the array
    addToArray(parsleyField.$element.attr('name'));

    // Do we have both fields within the array?
    if ($.inArray('field1', validFields) != -1 && $.inArray('field2', validFields) != -1) {
        // If so, remove the class
        $(".tab-nav-1").removeClass("tab-validation-error");
    } else {
        // Otherwise, add the class. There could be a time 
        $(".tab-nav-1").addClass("tab-validation-error");
    }
});

// Whenever an error occurs, lets remove the field from the array
$.listen('parsley:field:error', function (parsleyField) {
    removeFromArray(parsleyField.$element.attr('name'));
});

/**
 * Adds a string to an array
 */
function addToArray(fieldName) {
    // For our case, we're just adding the value if it matches our fields
    if ($.inArray(fieldName, validFields) === -1 && (fieldName == 'field1' || fieldName == 'field2')) {
        validFields.push(fieldName);
    }
}

/**
 * Removes a string from an array
 */
function removeFromArray(fieldName) {
    // For this case, we discard the fields that don't match the fields we need
    if (fieldName != 'field1' && fieldName != 'field2')
        return;

    // So, add the field if it doesn't exist in the array
    if ($.inArray(fieldName, validFields) != -1) {
        for(var i = validFields.length - 1; i >= 0; i--) {
            validFields.splice(i, 1);
        }
    }
}