How to prevent spaces and full stops in input fiel

2019-08-06 00:45发布

I have the following to disallow spaces

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

It works well for spaces but how can I also disallow full stops as well?

3条回答
Anthone
2楼-- · 2019-08-06 01:35

Below is the sample html and javscript you just wanted to add /./g for checking for .

<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>
查看更多
forever°为你锁心
3楼-- · 2019-08-06 01:39

If not its not necessary to use regex you can use

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

or if required

if(value.match(/\./g) != null) {
    alert("Dots not allowed");
}
查看更多
放我归山
4楼-- · 2019-08-06 01:41

Try this

    function nospaces(t){
        if(t.value.match(/\s|\./g)){
            alert('Username Cannot Have Spaces or Full Stops');
            t.value=t.value.replace(/\s/g,'');
        }
    }
查看更多
登录 后发表回答