【问题标题】:How to remove empty space in a input field and re-assign the trim value back如何删除输入字段中的空白并重新分配修剪值
【发布时间】:2014-07-24 05:56:49
【问题描述】:

我正在做电子邮件验证;在电子邮件字段中,用户可以放置空格。

所以我决定$trim 输入值并重新分配给输入字段。

它可以正常工作,没有任何问题,但是当我使用空格键几次并从输入中聚焦并返回时,输入字段中输入的空格。

虽然我正在修剪每个 input 事件 - 我不知道为什么空间与 input 字段。

请问有什么正确的方法吗?

这是我的尝试:

$('#email').on('input change',function(){
    this.value = $.trim(this.value); //re-assigning trimmed value, but not works when enterning space and focus out. when focus in the space being in the input
    validateEmail.init(this.value);
    if(validateEmail.done()){
        console.log('this is correct');
    }
});

//enter some space and focus out, then come back to input field you can see white spaces in the field

Live Demo

【问题讨论】:

  • 真的需要去掉输入框中的每个空格吗?为什么在将其传递给您的电子邮件验证时不直接修剪它? (validateEmail.init($.trim(this.value));)
  • 在 FF 中可以正常工作,但在 chrome 中不行
  • 我想基本上避免空格,因为这是电子邮件地址。再次,用户也可以复制粘贴一些不需要的空白。它在输入字段中变得非常冗长。
  • 现在代码已更新,现在它在开始时使用多个空格,最后它将删除所有空格试试这个...

标签: javascript jquery validation email trim


【解决方案1】:

嘿,我看过你的例子..

我已经更改了其中的绑定并且它按预期工作......

$('#email').on('keyup  change',function(){

     var text = $.trim($(this).val() )
     this.value="";      
     this.value=text;

    validateEmail.init(this.value);
    if(validateEmail.done()){
        console.log('this is correct');
    }
});

工作示例:-http://jsfiddle.net/SG6YN/10/

现在如果用户尝试粘贴带有空格的文本,那么它将删除这些空格..

谢谢

【讨论】:

  • 那么,根据您的说法input 有问题吗?我试过没有按预期工作。请在 chrome 浏览器中测试 pelase
  • 嘿,我已经更新了它的代码......你现在可以检查一下,它将删除开始和结束的所有空格
  • 是的,它正在工作。我使用 Rohand 的想法更新了您的代码,如下所示:var value = $.trim(this.value).replace(/\s+/g,''); - 工作正常
【解决方案2】:

限制用户在字段中输入空格

$('#email').keydown(function(e) {
        if (e.keyCode == 32) // 32 is the ASCII value for a space
            e.preventDefault();
    });

但如果用户复制并粘贴包含文本的空格,则它不起作用。所以在你的 onChange 函数上添加以下代码

$('#email').on('input change',function(){
    $(this).val($(this).val().replace(/\s+/g, ''));
    validateEmail.init(this.value);
    if(validateEmail.done()){
        console.log('this is correct');
    }
});

工作小提琴是here

【讨论】:

  • 尝试在start中添加多个空格并粘贴到文本框中会不行...
  • 它工作正常。我在 chrome、mozilla 中进行了测试。在哪个浏览器中不起作用
  • 在 chrome 中尝试这个关键字“文本”忽略其中的“(开头和结尾有 3 个空格)
猜你喜欢
  • 2011-05-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-09
  • 1970-01-01
  • 2013-10-21
  • 1970-01-01
  • 2010-11-14
  • 1970-01-01
相关资源
最近更新 更多