valid element is not highlighted when user clicks the submit button

359 Views Asked by At

I am currently using jQuery validation plugin to validate my form fields. I've set a rule where the username field is not required, the account name field is required and the comments textarea field is not required. When user clicks the "save" button, the 'has-error' class will highlight the invalid element. However, the 'has-success' class did not highlight the textarea valid element. Why is that so? Here is a screenshot of my problem, the desired result as well as my codes

Error picture, textarea not highlighted Error picture, textarea not highlighted

Desired result Desired result

 $(document).ready(function () {
        $.validator.setDefaults({

            errorClass: 'help-block',


            highlight: function (element) {
                $(element)
                    .closest('.form-group')
                    .addClass('has-error');

            },

            unhighlight: function (element) {
                $(element)
                    .closest('.form-group')
                    .removeClass('has-error')
                    .addClass('has-success');
            }
        });

        $('#dataForm').validate({
            rules: {
                userNameInput: {
                    required: false
                },
                accountNameInput: {
                    required: true
                },
                commentInput: {
                    required: false
                }
            }
        });

    });

    $('#saveButton').on('click', function () {

        if ($('#dataForm').valid() == true) {

        }

        alert('nice');
    });
<form id="dataForm" method="post" action="#">
    <div class="form-group col-md-12">
        <label class="control-label col-md-4" for="accountNameInput">Account name</label>
        <input type="text" id="accountNameInput" name="accountNameInput" class="form-control font-bold"
               maxlength="100" placeholder="Account name" value="" />
    </div>

    <div class="form-group col-md-12">
        <label class="control-label  col-md-4" for="userNameInput">userName</label>
        <input type="text" id="userNameInput" name="userNameInput" class="form-control font-bold"
               maxlength="100" placeholder="userName" value="" />
    </div>

    <div class="form-group col-md-12">
        <label class="control-label col-md-4" for="commentInput">Comments</label>
        <textarea class="form-control" id="commentInput" rows="5"></textarea>
    </div>

    <input type="button" class="btn btn-primary" value="Save" id="saveButton" />

</form>

0

There are 0 best solutions below