Search code examples
jqueryjquery-validate

how to add error icon and custom validation message using jQuery Validate?


I Would like to add error icon and custom validation message using jQuery Validate plugin. Like this

enter image description here

Here is my html code,

    <input type="text" id="firstName" name="firstName" class="required" />
    <input type="text" name="lastName" class="required" /> <br>

    <input id="email" type="text" name="email" class="required" /> <br>

Here is my Html code,

I have tried with errorPlacement function, however for some reason i am not able to get error message below the control. I have used prepentTo, appendTo, all jquery function to do this. but no luck!!!

function validateForm(){
           
            $("#register").validate({
               
               
                rules: {
                    firstName: {
                        required: true,
                        minlength: 2
                    }
                },
                    errorPlacement: function(error, element) {
                        error.insertAfter(element); 
                            
                    },
                    
            });
        }

Thanks


Solution

  • for some reason i am not able to get error message below the control.

    By default, the error message is put inside a label which is an inline element.

    Use the errorElement option to change this into a block level element and it will wrap automatically.

    See: http://jsfiddle.net/kH9NL/

    $(document).ready(function () {
    
        $('#myform').validate({ 
            errorElement: "div",
            rules: {
                field1: {
                    required: true
                },
                field2: {
                    required: true
                }
            }
        });
    
    });
    

    You must use the highlight and unhighlight callback functions to manipulate the placement and toggling of your icons.

    This answer provides a concrete example using these two callback functions:

    https://stackoverflow.com/a/14900826/594235