如何防止使用javascript空格和句号在输入字段(How to prevent spaces a

2019-10-18 04:52发布

我必须禁止空间以下

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

它非常适用空间,但我怎么也不允许句号呢?

Answer 1:

尝试这个

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


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


Answer 3:

如果不是它没有必要使用正则表达式 ,你可以使用

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

或者如果需要的话

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


文章来源: How to prevent spaces and full stops in input field with javascript