0

I am using jquery validation with the jquery-validation-bootstrap-tooltip plugin 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 " funny cat" or "funny cat" will only be validated and saved as "funny cat".

Here is my code:

$('#custom-tag').validate({
    onkeyup: function (element, event) {
            if (event.which === 9 && this.elementValue(element) === "") {
                return;
            } else if (this.elementValue(element).length < 3 ) {
               return;
            } else {
                this.element(element);
            }
    },
    rules: {
      tag: {
        maxlength: 25,
        minlength: 2
      }
    },
    tooltip_options: {
      tag: { placement: 'right', animation: false }
    }
  });

I found this post that is related but can't figure out how to apply it to my case.

I think I might have to make my own method that ignores extra whitespace when evaluating the input and use before save to make sure these whitespaces are removed before saving. I could use some help the code.

http://jsfiddle.net/QfKk7/

ANSWER:

I used the answer below to create a new method:

$.validator.addMethod(
    "maxLen", 
    function (value, element, param) {
      var value = this.elementValue(element).replace(/\s+/g, ' ').trim();
      if (value.length > param) {
        return false;
      } else {
        return true;
      }
  }, "error message");

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.

Community
  • 1
  • 1
user4584963
  • 2,403
  • 7
  • 30
  • 62

1 Answers1

2

First replace multiple whitespaces with a single one, ant then trim the string.

function (element, event) {
  var value = this.elementValue(element).replace(/\s+/g, ' ').trim();
  if (event.which === 9 && value === "") {
    return;
  } else if (value.length < 3 ) {
    return;
  } else {
    this.element(element);
  }
}
dsdenes
  • 1,025
  • 6
  • 15
  • Doesn't seem to work this way. It is still counting the unwanted spaces in the validation. Do you think you could create a custom method using that that ignores the whitespaces and that I could use instead of maxlength? [addMethod](http://jqueryvalidation.org/jQuery.validator.addMethod) – user4584963 Dec 11 '15 at 22:19
  • I used your code to add a method. I just had to change the regular expression to `/\s+/g, ' '` to get it to work. – user4584963 Dec 13 '15 at 01:07