Parsley 2: Custom validation and single message

Use a custom vaildation that combines multiple inputs and presents a single message

by 3q7ndcohsh

HTML

<script src="http://parsleyjs.org/dist/parsley.min.js"></script>
<form class="form-inline" role="form" id="myForm">
    <table>
        <tr>
            <td>Field1A</td>
            <td><input type="text" name="field1A" id="field1A" /></td>
            <td>Field1B</td>
            <td><input type="text" name="field1B" id="field1B" /></td>
        </tr>
        <tr>
            <td>Field2A</td>
            <td><input type="text" name="field2A" id="field2A" /></td>
            <td>Field2B</td>
            <td><input type="text" name="field2B" id="field2B" /></td>
        </tr>
        <tr>
            <td>Field3A</td>
            <td><input type="text" name="field3A" id="field3A" /></td>
            <td>Field3B</td>
            <td><input type="text" name="field3B" id="field3B" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <button type="submit" class="btn btn-default">test</button>
            </td>
        </tr>
        <tr>
            <td colspan="2" id="form-message-holder"></td>
        </tr>
    </table>
</form>

JavaScript

$('#myForm').parsley();

// 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');
    }
});

$("#myForm" ).submit(function( event ) {
    $(this).parsley().validate();
    if ($(this).parsley().isValid()) {
        console.log('valid');
    }
    event.preventDefault();
});