Parsley.js Validation if 1 of 4 Fields Has a Value

1.8k Views Asked by At

On a form there are 4 text inputs.
If at least 1 of them has a value then all remaining fields must have a value.
Is it possible to configure Parsley.js for this validation?

1

There are 1 best solutions below

2
On BEST ANSWER

Yes, it is possible. However, there is no default configuration to do it.

This means that you must create that logic in your javascript and destroy / bind parsley in each case.

Take a look at this code (jsfiddle available):

<form class="form-inline" method="post" id="myForm">
    <input type="text" id="field1" name="field1" />
    <input type="text" id="field2" name="field2" />
    <input type="text" id="field3" name="field3" />
    <input type="text" id="field4" name="field4" />
    <button type="submit" class="btn btn-default">test</button>
</form>

<script>
    $('#myForm').parsley();

    $("#field1, #field2, #field3, #field4").on('change', function() {
        if ($("#field1").val().length > 0 ||
            $("#field2").val().length > 0 ||
            $("#field3").val().length > 0 ||
            $("#field4").val().length > 0 )
        {
            // If any field is filled, set attr required
            $("#field1, #field2, #field3, #field4").attr("required", "required");
        } else {
            // if all fields are empty, remove required attr
            $("#field1, #field2, #field3, #field4").removeAttr("required");
        }
        // destroy ParsleyForm instance
        $('#myForm').parsley().destroy();

        // bind parsley
        $('#myForm').parsley();
    });

    $("#myForm" ).on('submit', function( event ) {
        $(this).parsley().validate();
        if ($(this).parsley().isValid()) {
            alert('form is valid');
        }
        event.preventDefault();
    });

</script>