elchente23
elchente23

Reputation: 183

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

enter image description here

Any way to replace the text with the corresponding one?

Regards

Upvotes: 0

Views: 4278

Answers (1)

Sparky
Sparky

Reputation: 98718

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.

Upvotes: 1

Related Questions