如何使用javascript防止输入字段中出现空格和句号

问题描述 投票:1回答: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,'');

    }

}

HTML

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

它对空间效果很好,但是我怎么也不能禁止句号?

javascript forms validation field
3个回答
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,'');
        }
    }

2
投票

下面是您只想添加/./g用于检查的示例html和javscript。

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

1
投票

如果没有必要使用regex,则可以使用

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

或(如果需要)

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

0
投票

[每次您提出答案时,您都会忽略起点和终点,人们来这里寻求帮助,并给他们1/2的脚本。它进入头部还是身体?你一文不值。

© www.soinside.com 2019 - 2024. All rights reserved.