title: JQuery Validation - trim whitespaces
body: <p>I am using <a href="http://jqueryvalidation.org/validate" rel="nofollow noreferrer">jquery validation</a> with the <a href="https://github.com/Thrilleratplay/jquery-validation-bootstrap-tooltip" rel="nofollow noreferrer">jquery-validation-bootstrap-tooltip plugin</a> in my rails app.  I would like to trim whitespaces so that spaces at the start and end are removed and don't count towards the validation and also any whitespace in the middle of the string is removed if there is a whitespace before it.  I want to be sure that things like <code>"    funny cat"</code> or <code>"funny    cat"</code> will only be validated and saved as "funny cat".</p>
  
  <p>Here is my code:</p>
  
  <pre><code>$('#custom-tag').validate({
      onkeyup: function (element, event) {
              if (event.which === 9 &amp;&amp; this.elementValue(element) === "") {
                  return;
              } else if (this.elementValue(element).length &lt; 3 ) {
                 return;
              } else {
                  this.element(element);
              }
      },
      rules: {
        tag: {
          maxlength: 25,
          minlength: 2
        }
      },
      tooltip_options: {
        tag: { placement: 'right', animation: false }
      }
    });
  </code></pre>
  
  <p>I found this <a href="https://stackoverflow.com/questions/1827483/jquery-validate-plugin-how-to-trim-values-before-form-validation/6472021#comment22281032_6472021">post</a> that is related but can't figure out how to apply it to my case.</p>
  
  <p>I think I might have to make my own method that ignores extra whitespace when evaluating the input and use <code>before save</code> to make sure these whitespaces are removed before saving.  I could use some help the code.</p>
  
  <p><a href="http://jsfiddle.net/QfKk7/" rel="nofollow noreferrer">http://jsfiddle.net/QfKk7/</a></p>
  
  <p>ANSWER:</p>
  
  <p>I used the answer below to create a new method:</p>
  
  <pre><code>$.validator.addMethod(
      "maxLen", 
      function (value, element, param) {
        var value = this.elementValue(element).replace(/\s+/g, ' ').trim();
        if (value.length &gt; param) {
          return false;
        } else {
          return true;
        }
    }, "error message");
  </code></pre>
  
  <p>Adding the g to the regular expression made it work the way I wanted.  Now I just have to use rails squish before saving to the database.</p>