2

How to validate input fields inside a modal popup using ParsleyJS?

I have already an error container in layout page which works for page level input fields. I want to validate input fields in a modal popup and the error message should also be displayed in the popup.

Carol-Theodor Pelu
  • 906
  • 2
  • 10
  • 26
Abi
  • 283
  • 3
  • 16

2 Answers2

3

To display validation errors inside a specific the Modal, you will need to use this data attribute on the input elements:

data-parsley-errors-container="#modal_div_error_container"

This is how you can validate the input fields inside your Modal <div>

JS:

$(function(){
    var parsley_valiation_options = {
         //errorsWrapper: '',
         errorTemplate: '<span class="error-msg"></span>',
         errorClass: 'error',
    }
    //check if modal_div element exists on the page
    if ($('#modal_div').length > 0) {

        //Attach Parsley validation to the modal input elements
        $('#modal_div input').parsley(parsley_valiation_options);

        //On modal submit button click, validate all the input fields
        $('#modal_div_submit_button').click(function(event) {
            event.preventDefault();

            var isValid = true;

            $('#modal_div input').each(function(){
                if($(this).parsley().validate() !== true)
                    isValid = false;
            })

            if(isValid) {
                alert("All fields are validated !");
            }
        });
    }
});

HTML:

<!-- Modal -->
<div id="modal_div">
    <!-- Modal div error container (Validation error messages will display here)-->
    <div id="modal_div_error_container"></div>


    <label for="name">
        Name (should be alphanumeric and min length: 7)
    </label>

    <input type="text" id="name" name="name" data-parsley-minlength="7" data-parsley-minlength-message="Name must be at least 7 characters" data-parsley-required="true" data-parsley-errors-container="#modal_div_error_container"/>

    <button type="submit" id="modal_div_submit_button">Submit</button>
</div>
Rahul Gupta
  • 9,775
  • 7
  • 56
  • 69
-1

You need to use button type as a "submit" instead of "button". Then that might solve your issue.