简体   繁体   中英

select2 custom error message with jQuery validation plugin

When I try to validate a select2 what I get is the same text as the label

 <div class="row">
     <div class="col-sm-12">
         <div class="form-group">
             <label for="cboMetodoPago">Método de pago <span class="required"></span></label>
             <select class="form-control select2-nosearch" id="cboMetodoPago" name="cboMetodoPago" required></select>
         </div>
     </div>
 </div>

This is how I configure the plugin

    $(".formsave").validate({
        highlight: function (element) {
            jQuery(element).closest('.form-group').addClass('has-error');
        },
        success: function (element) {
            jQuery(element).closest('.form-group').removeClass('has-error');
        },
        ignore: ["input[type=hidden]"],
        onfocusout: false,
        invalidHandler: function (form, validator) {
            var error = validator.numberOfInvalids();

            if (error) {
                validator.errorList[0].element.focus();
            }
        },
        message: {
            cboMetodoPago: {
                required: "Este campo es obligatorio"
            }
       }
    });

And the text I get is the same as the label inside the form-group

在此处输入图片说明

Any way to replace the text with the corresponding one?

Regards

The object is called messages , not message as you have it.

messages: { // <- "messages", not "message"
    cboMetodoPago: {
        required: "Este campo es obligatorio"
    }
}

Based on your usage of highlight , you should use unhighlight instead of success .

highlight: function (element) {
    jQuery(element).closest('.form-group').addClass('has-error');
},
unhighlight: function (element) {
    jQuery(element).closest('.form-group').removeClass('has-error');
},

The success function is really meant for controlling the error message element, which is normally hidden when the element passes validation. In other words, you can leverage the error label when the element passes validation to give another message or icon, like "passed" or a green checkmark.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM