how to add erroricon and custom validation message using jquery?

微笑、不失礼 提交于 2020-05-23 07:37:07

问题


I Would like to add error icon and custom validation message using Jquery 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


回答1:


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




回答2:


From the documentation of options you can pass to validate function

errorPlacement: function(error, element) {
  error.appendTo( element.parent("td").next("td") );
}

so your code should be:

errorPlacement: function(error, element) {
  error.appendTo(element.parent()); 
}

or something like these.

Then you can use wrapper property to specify a container for your errors.

Moreover you can use errorClass property to change error class.

And you can use messages property to set custom message.

Then you have to specify rules for the selector you choose.

You can take a look also here

Hope this helps



来源:https://stackoverflow.com/questions/15836465/how-to-add-erroricon-and-custom-validation-message-using-jquery

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