Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validate display error message in div

I am new with jQuery validation and learing so I don't have any idea about this. Now I am using jQuery Validate plugin and want to display error message inside div element. I have created div for every error message.

For example I have Name input field and want to display error message inside nameError div.

<div>
    <label for="name">Name</label>
    <input id='name' name="name" value="" />
</div>
<div id="nameError">
    <!-- Display Name Error Here  -->
</div>

Is it possible for jQuery Validation Plugin? I have no idea that why I am posting here to get help from you.

MY JQUERY CODE IS:

$(function () {
    $.validator.addMethod("regex", function (value, element, regexpr) {
        return regexpr.test(value);
    }, "Please enter a valid name.");

    $("#myForm").validate({
        rules: {
            name: {
                required: true,
                regex: /^[A-Za-z]+$/
            }
        }
    });
});

MY JSFIIDLE

Thanks.

like image 456
Mr.Happy Avatar asked Apr 11 '14 04:04

Mr.Happy


Video Answer


2 Answers

Here's a quick sample: http://jsfiddle.net/4PuJL/7/

jQuery.validator.setDefaults({
    errorPlacement: function(error, element) {
        error.appendTo('#nameError');
    }
});
like image 126
MarioD Avatar answered Oct 21 '22 10:10

MarioD


You may add a check in errorPlacement handler like below: Please note that errorPlacement function is called for each error, if you need more handling on error message, please check for invalidHandler

jQuery.validator.setDefaults({
    errorPlacement: function(error, element) {
        if (element.attr("name") == "name" )  //Id of input field
            error.appendTo('#nameError');
        if (element.attr("name") == "anotherInputField" )  //Id of input field
            error.appendTo('#anotherInputFieldError');
    }
});
like image 45
Ken Avatar answered Oct 21 '22 10:10

Ken