Parsley.js - Display errors near fields AND in a combined list above form

后端 未结 1 1942
萌比男神i
萌比男神i 2021-02-06 16:17
  1. Is it possible to configure Parsley.js to display its error messages both... a) next to individual fields, AND b) in a combined list elsewhere on the page ...at the sam

相关标签:
1条回答
  • 2021-02-06 16:34

    To accomplish what you want, you need to use Parsley's events. Take a look at the event's description and the comments on the below code.

    <div class="validation-errors"></div>
    <form>
        <input type="text" name="field1" required />
        <input type="text" name="field2" required />
        <input type="submit" />
    </form>
    
    <script>
        $(document).ready(function() {
            // validate form
            $("form").parsley();
    
            // Before each validation, clear the validation-errors of the div
            $.listen('parsley:form:validate', function() {
                $('.validation-errors').html('');
            });
    
            // When a field has an error
            $.listen('parsley:field:error', function(fieldInstance){
                // Get the error messages
                var messages = ParsleyUI.getErrorsMessages(fieldInstance);
    
                // Get the field's name
                var fieldName = fieldInstance.$element.attr('name');
    
                // Loop through all the messages
                for (var i in messages) {
                    // Create a message for each error
                    var $m = $('<p><a class="focus-' + fieldName + '" href="#">' + fieldName + ': ' + messages[i] + '</a><p>');
    
                    // Append the errors to the div
                    $('.validation-errors').append($m);
                }
            });        
        });
    
        // When there's a click on a error message from the div
        $(document).on('click', 'a[class^="focus-"]', function(){
            // take the field's name from the class
            var parts = $(this).attr('class').split('-');
    
            $("[name=" + parts[1] + "]").focus();
        });
    </script>
    

    Here's a demo in Jsfiddle.

    Important note: the code I'm providing uses the events available in Parsley 2.0.* . If you're using the newly Parsley 2.1.*, you should use the correct events. Instead of parsley:form:validate use form:validate and replace parsley:field:error by field:error.

    0 讨论(0)
提交回复
热议问题