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

匆匆过客 提交于 2019-12-03 08:28:54

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!