user3732216
user3732216

Reputation: 1589

jQuery Validation with Error Placement

I'm currently working on login form and trying to develop the functionality I need it to do when the validation does not pass on the client side.

This is the current HTML I have that is rendered before the login form is validated. I'm wanting to place the error after the div class input-group. It is still placing it after the form-control instead.

<div class="input-group mb15">
    <span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
    <input type="text" class="form-control" placeholder="Email Address" name="email_address">
</div><!-- input-group -->
<div class="input-group mb15">
    <span class="input-group-addon"><i class="glyphicon glyphicon-lock"></i></span>
    <input type="password" class="form-control" placeholder="Password" name="password">
</div><!-- input-group -->

jQuery Validation Process

$("#login-form").validate({      
    highlight: function(element) {
        $(element).closest('.input-group').removeClass('has-success').addClass('has-error');
    },
    errorPlacement: function(error, element) {
        error.appendTo(element.parent('.input-group'));
    }      
});

Upvotes: 0

Views: 7954

Answers (1)

Sparky
Sparky

Reputation: 98758

The plugin creates and then automatically toggles the error label, so don't use appendTo() for this. Also your append is appending the label inside of the div, which puts it in the same exact place it would have been originally, just after the input element.

Simply keep the default insertAfter() and adjust the jQuery selector.

errorPlacement: function(error, element) {
    error.insertAfter(element.parent('.input-group'));
}

If you're seeing any CSS issues, then it's likely related to a failure to implement the unhighlight callback function when using highlight.

$("#login-form").validate({      
    highlight: function(element) {
        $(element).closest('.input-group').removeClass('has-success').addClass('has-error');
    },
    unhighlight: function(element) {
        $(element).closest('.input-group').addClass('has-success').removeClass('has-error');
    },
    errorPlacement: function(error, element) {
        error.insertAfter(element.parent('.input-group'));
    }      
});

Upvotes: 1

Related Questions