jqueryvalidationerrorplacement

jQuery validation error message placement


Ok so I am using the jQuery validation plugin to check for errors on a simple form. Everything is working except the error placement. I am trying to get my error messages placed into a SPAN element just after the INPUT that contains an error. For some reason the code below is placing the error message in what seems to be a whole new LABEL element. Any idea what I am doing wrong here?

my html

    <form action="" id="contact" method="POST">
       <p>
         <label for="name">Name:</label>
         <input type="text" name="name" id="name" class="text proper"/><span class="errMsg"></span>
       </p>
       <p>
         <label for="email">* Email:</label>
         <input type="text" name="email" id="email" class="required email text"/><span class="errMsg"></span>
       </p>
       <p>
         <label for="extra">*Question:</label>
         <textarea name="onlyText" id="onlyText" class=""></textarea><span class="errMsg"></span>
       </p>

       <button type="submit" id="send">Send Now</button>
       <div id="results"></div>
    </form>

my jQuery

    <script>
      jQuery(document).ready(function($){           
        $.validator.addMethod("regex",function(value, element, regexp) {
         var check = false;
         var re = new RegExp(regexp);
         return this.optional(element) || re.test(value);
        },
          "No special Characters allowed here. Use only upper and lowercase letters (A through Z; a through z), numbers and punctuation marks (. , ; ? ' ' \" -  ~ ! @ $ % ^ & * (     ) _ + / < > { } )"
        );
        $("#contact").validate({
         rules: {
            onlyText:{
              required: true,
              maxlength: 8000,
              regex: /^[0-9A-Za-z\s`~!@$%^&*()+{}|;'",.<>\/?\\-]+$/
            },
            name:{
              required: false,
              maxlength: 75,
              regex: /^[0-9A-Za-z\s`~!@$%^&*()+{}|;'",.<>\/?\\-]+$/
           }
         } , 
          errorPlacement: function(error, element) {
          error.appendTo( element.next() );  //* THIS IS WHERE I AM HAVING TROUBLE WITH
     });
     });
   </script>

Solution

  • You can avoid the hassle and use the errorElement and errorClass options to have the plugin add the correct element for you:

    $("#contact").validate({
        errorElement: 'span',
        errorClass: 'errMsg',
        rules: {
                onlyText:{
                  required: true,
                  maxlength: 8000,
                  regex: /^[0-9A-Za-z\s`~!@$%^&*()+{}|;'",.<>\/?\\-]+$/
                },
                name:{
                  required: false,
                  maxlength: 75,
                  regex: /^[0-9A-Za-z\s`~!@$%^&*()+{}|;'",.<>\/?\\-]+$/
               }
             } 
        });