56

This looks very simply, but I can't figure it out. I'm using the jquery validate plugin. I'm trying to validate <input name=first> and <input name=second> to output the error messages into:

<span id="errNm2"></span> <span id="errNm1"></span>

I already started writing the errorPlacement: which is where you customize your error message location.

How can I put the errors message in those <span>?

$(document).ready(function () {
    $('#form').validate({
        errorPlacement: function(error, element) {
            error.append($('.errorTxt span'));
        },
        rules,
});
<input type="text" name="first"/>
<input type="text" name="second"/>

<div class="errorTxt">
   <span id="errNm2"></span>
   <span id="errNm1"></span>
</div>

8 Answers 8

118

What you should use is the errorLabelContainer

jQuery(function($) {
  var validator = $('#form').validate({
    rules: {
      first: {
        required: true
      },
      second: {
        required: true
      }
    },
    messages: {},
    errorElement : 'div',
    errorLabelContainer: '.errorTxt'
  });
});
.errorTxt{
  border: 1px solid red;
  min-height: 20px;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>

<form id="form" method="post" action="">
  <input type="text" name="first" />
  <input type="text" name="second" />
  <div class="errorTxt"></div>
  <input type="submit" class="button" value="Submit" />
</form>


If you want to retain your structure then

jQuery(function($) {
  var validator = $('#form').validate({
    rules: {
      first: {
        required: true
      },
      second: {
        required: true
      }
    },
    messages: {},
    errorPlacement: function(error, element) {
      var placement = $(element).data('error');
      if (placement) {
        $(placement).append(error)
      } else {
        error.insertAfter(element);
      }
    }
  });
});
#errNm1 {
  border: 1px solid red;
}
#errNm2 {
  border: 1px solid green;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/jquery.validate.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.12.0/additional-methods.js"></script>

<form id="form" method="post" action="">
  <input type="text" name="first" data-error="#errNm1" />
  <input type="text" name="second" data-error="#errNm2" />
  <div class="errorTxt">
    <span id="errNm2"></span>
    <span id="errNm1"></span>
  </div>
  <input type="submit" class="button" value="Submit" />
</form>

Sign up to request clarification or add additional context in comments.

1 Comment

I would suggest a small change in the code $(placement).append(error) ... here if the validation is triggered multiple times (Eg: multiple submit button click) then the error also gets appended multiple times. So I think its better to have html instead of append ... $(placement).html(error)
22

You can simply create extra conditions which match the fields you require in the same function. For example, using your code above...

$(document).ready(function () {
    $('#form').validate({
        errorPlacement: function(error, element) {
            //Custom position: first name
            if (element.attr("name") == "first" ) {
                $("#errNm1").text(error);
            }
            //Custom position: second name
            else if (element.attr("name") == "second" ) {
                $("#errNm2").text(error);
            }
            // Default position: if no match is met (other fields)
            else {
                 error.append($('.errorTxt span'));
            }
        },
        rules
});

Hope that helps!

2 Comments

this almost worked for me. The only problem I have is the 'else' condition. How do change it to run the default validation placement?
This works, but consider instead Arun's solution using data attributes to allow you to specify this in the markup and not have to add a new condition to the errorPlacement function for each input, which isn't very DRY.
4
 if (e.attr("name") == "firstName" ) {
     $("#firstName__validate").text($(error).text());
     console.log($(error).html());
 }

Try this get text of error object

Comments

4

Just add an empty label tag with the same id as input field has + "-error", for example.

<input id="myID1" required>
<input id="myID2" required>
<div>
    <label id="myID1-error" class="error" for="myID1"></label>
    <label id="myID2-error" class="error" for="myID2"></label>
</div>

Comments

2

HTML

<form ... id ="GoogleMapsApiKeyForm">
    ...
    <input name="GoogleMapsAPIKey" type="text" class="form-control" placeholder="Enter Google maps API key" />
    ....
    <span class="text-danger" id="GoogleMapsAPIKey-errorMsg"></span>'
    ...
    <button type="submit" class="btn btn-primary">Save</button>
</form>

Javascript

$(function () {
    $("#GoogleMapsApiKeyForm").validate({
      rules: {
          GoogleMapsAPIKey: {
              required: true
          }
        },
        messages: {
            GoogleMapsAPIKey: 'Google maps api key is required',
        },
        errorPlacement: function (error, element) {
            if (element.attr("name") == "GoogleMapsAPIKey")
                $("#GoogleMapsAPIKey-errorMsg").html(error);
        },
        submitHandler: function (form) {
           // form.submit(); //if you need Ajax submit follow for rest of code below
        }
    });

    //If you want to use ajax
    $("#GoogleMapsApiKeyForm").submit(function (e) {
        e.preventDefault();
        if (!$("#GoogleMapsApiKeyForm").valid())
            return;

       //Put your ajax call here
    });
});

Comments

1

This Worked for me

Actually error is a array which contain error message and other values for elements we pass, you can console.log(error); and see. Inside if condition "error.appendTo($(element).parents('div').find($('.errorEmail')));" Is nothing but finding html element in code and passing the error message.

    $("form[name='contactUs']").validate({
rules: {
    message: 'required',
    name: "required",
    phone_number: {
        required: true,
        minlength: 10,
        maxlength: 10,
        number: false
    },
    email: {
        required: true,
        email: true
    }
},
messages: {
    name: "Please enter your name",
    email: "Please enter a valid email address",
    message: "Please enter your message",
    phone_number: "Please enter a valid mobile number"
},
errorPlacement: function(error, element) {
        $("#errorText").empty();

        if(error[0].htmlFor == 'name')
        {
            error.appendTo($(element).parents('div').find($('.errorName')));
        }
        if(error[0].htmlFor == 'email')
        {
            error.appendTo($(element).parents('div').find($('.errorEmail')));
        }
        if(error[0].htmlFor == 'phone_number')
        {
            error.appendTo($(element).parents('div').find($('.errorMobile')));
        }
        if(error[0].htmlFor == 'message')
        {
            error.appendTo($(element).parents('div').find($('.errorMessage')));
        }
      }
    });

Comments

0

Add this code in your validate method:

 errorLabelContainer: '#errors'

and in your html, put simply this where you want to catch the error:

<div id="errors"></div>

All the errors will be held in the div, independently of your input box.

It worked very fine for me.

Comments

0

Here's the code with the jQuery validation logic to display the error message in a different place:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.5/jquery.validate.min.js"></script>
    <script>
        $(document).ready(function() {
            $('#form').validate({
                errorPlacement: function(error, element) {
                    if (element.attr("name") == "policy_accepted") {
                        error.appendTo($('#policy_accepted_error'))
                    } else {
                        error.insertAfter(element);
                    }
                },
                errorClass: 'text-danger',
                rules: {
                    policy_accepted: {
                        required: true,
                    }
                },
                messages: {
                  policy_accepted: {
                        required: "You have to accept our terms & condition",
                    },
                } 
            });
        });
    </script>
<form id="form" method="post">
<div class="mb-3">
  <label class="lg">
    <input type="checkbox" name="policy_accepted" class="form-check-input me-2" value="1" />
    <span>
        I agree to the <a href="">guest policies</a> ,
        <a href="">cancellation policy</a>, and the guest
        refund policy.
    </span>
  </label>
  <p class="text-danger" id="policy_accepted_error"></p>
</div>

<button type="submit" class="large-btn">Continue to Booking</button>
</form>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.