【问题标题】:How to prevent spaces and full stops in input field with javascript如何使用javascript防止输入字段中的空格和句号
【发布时间】:2013-05-21 07:54:19
【问题描述】:

我有以下禁止空格

function nospaces(t){

    if(t.value.match(/\s/g)){

        alert('Username Cannot Have Spaces or Full Stops');

        t.value=t.value.replace(/\s/g,'');

    }

}

HTML

<input type="text" name="username" value="" onkeyup="nospaces(this)"/>

它适用于空格,但我如何也不允许句号?

【问题讨论】:

    标签: javascript forms validation field


    【解决方案1】:

    如果没有必要使用 regex 你可以使用

    if(value.indexOf('.') != -1) {
        alert("dots not allowed");
    }
    

    或者如果需要

    if(value.match(/\./g) != null) {
        alert("Dots not allowed");
    }
    

    【讨论】:

      【解决方案2】:

      下面是示例 html 和 javscript,您只是想添加 /./g 以检查 .

      <html>
      <input type="text" name="username" value="" onkeyup="nospaces(this)"/>
      <script>
      function nospaces(t){
      
          if( t.value.match(/\s/g) || t.value.match(/\./g)  ){
      
              alert('Username Cannot Have Spaces or Full Stops');
      
              t.value= (t.value.replace(/\s/g,'') .replace(/\./g,''));
      
          }
      
      }
      </script>
      </html>
      

      【讨论】:

        【解决方案3】:

        试试这个

            function nospaces(t){
                if(t.value.match(/\s|\./g)){
                    alert('Username Cannot Have Spaces or Full Stops');
                    t.value=t.value.replace(/\s/g,'');
                }
            }
        

        【讨论】:

        • 谢谢这很好用。我刚刚把最后一行改成了 t.value=t.value.replace(/\s|\./g,'');
        • 我试过了,但没有声望。一旦我得到一个好的代表,我会回来投票
        • 哦忘记了。我去过一次:)
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-16
        • 2017-03-08
        • 1970-01-01
        • 1970-01-01
        • 2019-01-16
        • 1970-01-01
        相关资源
        最近更新 更多