简体   繁体   中英

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

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?

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM