'jQuery Validation for 5 maximum values in input field following comma seperator

I am using autocomplete dropdown by following this below link,

https://www.jqueryscript.net/form/tags-autocomplete-dropdown.html

Following is my HTML and jQuery Code,

<div class="pf-field">
     <input type="text" name="categories" id="categories" name="categories" class="tags_input">
</div>

<script>
    $(function(){
    var data = [
        'History',
        'Civics',
        'Geogpraphy',
        'Science',
        'Economics',
        'Arts',
        'Chemistry',
        'Mathematics',
        'Language',
        'Computer',
    ];

    $(".tags_input").tagComplete({

                keylimit: 1,
                hide: false,
                autocomplete: {
                    data: data
                }
        });
});
</script>

Everything is working properly till here. Users can add as many values as they wants. However, I want to limit this by allowing user not to add more than or less than 5 values.

$(function(){
    var $profile = $('#profile');
    if($profile.length){
        $profile.validate({
            errorElement: 'span',
            rules:{
                categories:{
                    required: true
                }

            },
            messages:{
                categories:{
                    required:'Categories are mandatory!'
                }
            }
        })
    }
})

also, This same jQuery Validation is working fine with other input fields but not on working with this autocomplete dropdown.

Can you help me out please, I am find solution about this since last week.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source