Display error message in a separate div using jQuery validation

I am using jQuery validation and I want to display the error message in div <div class="alert alert-error" id="errorContainer"> . The default value displayed below the forms does not work with my form design.

The script check is linked to the page on which I have the form, and it looks like this:

  $(function validate() { var rules = { rules: { full_name: { minlength: 2, maxlength: 50, required: true }, address: { minlength: 5, required: true }, city: { minlength: 2, required: true }, state: { minlength: 2, maxlength: 2, required: true }, zip: { minlength:5, maxlength:5, required: true }, phone: { required: true, phoneUS: true }, phone_other: { required: true, phoneUS: true }, email: { required: true, email: true }, date_to_start: { required: true }, ssn: { required: true, ssn: true, }, salary: { required: true } } }; var validationObj = $.extend (rules, Application.validationRules); $('#employment-application').validate(validationObj); }); 

Now I tried to change $('#employment-application').validate(validationObj); to the code below, and also tried to add it to the end of the page on which I have a form, both gave negative results. It looks like the script is adding style="display:none;" to errorContainer and does not load any errors anywhere.

(tried changing $('#employment-application').validate(validationObj); to below)

 $("#employment-application").validate({ errorContainer: "#errorContainer", errorLabelContainer: "#errorContainer", errorElement: "li" }) 

So, redo, I want to use JQuery Form Validation and display error messages received in a separate div, because by default it does not work with my form design.

+4
source share
2 answers

You can use the errorPlacement parameter to pass the callback as follows: http://jsfiddle.net/cMhQ7/

I used the standard div id, which is the name of the input element combined with the suffix _validate , but you can change as you want.

HTML

 <form id="employment-application" method="post"> <input name="full_name" type="text" /> <div id="full_name_validate"></div> <input type="submit" /> </form> 

Javascript

 $(function validate() { var rules = { rules: { full_name: { minlength: 2, maxlength: 50, required: true }, }, errorPlacement: function (error, element) { var name = $(element).attr("name"); error.appendTo($("#" + name + "_validate")); }, }; $('#employment-application').validate(rules); }); 
+13
source

If you want to change the default layout to certain elements, you can use this enhancement. This implements the default behavior of the validate script.

  errorPlacement: function(error, element){ var name = $(element).attr("name"); var $obj = $("#" + name + "_validate"); if($obj.length){ error.appendTo($obj); } else { error.insertAfter(element); } }, 
+4
source

Source: https://habr.com/ru/post/1485399/


All Articles