jQuery Validate add and remove classes using callbacks [duplicate]

爱⌒轻易说出口 提交于 2021-02-05 07:52:05

问题


I am working with the jQuery Validate plugin and I am trying to use the errorPlacement and success callbacks to add and remove the bootstrap class has-error.

Currently, the errorPlacement callback works but since the success callback returns the error label (which I'm not using) I'm not sure what to do. I need access to my input again in success but I don't know how to do it.

$('#msform').validate({
    submitHandler: function (form) {
        alert('valid form submitted');
        return false; // for demo
    },
    errorPlacement: function(error, element) {
        $(element).parent().addClass('has-error');
        $(element).css('border-color', '#a94442');
    },
    success: function(label) {
        label.removeClass('has-error').text('ok');
    },
    invalidHandler: function(event, validator) {
        var errors = validator.numberOfInvalids();
    }
});

Can anybody help? Thanks.

Edit:

I think I should be using highlight and unhighlight via combining custom error placement with success is not working jquery validate plugin.


回答1:


So I found the answer pretty soon after I asked. I was using the wrong callbacks. For this type of desire you need to use highlight and unhighlight. But for some reason you also need to define errorPlacement if you don't want the added label.

$('#msform').validate({
    errorPlacement: function() {},
    highlight: function(element) {
        $(element).parent().addClass('has-error');
        $(element).css('border-color', '#a94442');
    },
    unhighlight: function(element) {
        $(element).parent().removeClass('has-error');
        $(element).css('border-color', '');
    },
    submitHandler: function (form) {
        alert('valid form submitted');
        return false; // for demo
    },
    invalidHandler: function(event, validator) {
        var errors = validator.numberOfInvalids();
    }
});


来源:https://stackoverflow.com/questions/38925416/jquery-validate-add-and-remove-classes-using-callbacks

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