JQuery验证 - 修剪空格 [英] JQuery Validation - trim whitespaces

查看:81
本文介绍了JQuery验证 - 修剪空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jquery validation 我的rails应用程序中的/ jquery-validation-bootstrap-tooltiprel =nofollow noreferrer> jquery-validation-bootstrap-tooltip插件。我想修剪空格,以便删除开头和结尾的空格,并且不计入验证,如果前面有空格,则删除字符串中间的任何空格。我想确保有趣的猫有趣的猫之类的内容只会被验证并保存为有趣的猫。

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

这是我的代码:

$('#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/

答案:

我用下面的答案创建了一个新方法:

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");

将g添加到正则表达式使其按照我想要的方式工作。现在我只需要在保存到数据库之前使用rails squish。

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.

推荐答案

首先用一个空格替换多个空格,然后是ant修剪弦乐。

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);
  }
}

这篇关于JQuery验证 - 修剪空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆