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.
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.