How to prevent spaces and full stops in input field with javascript

烂漫一生 提交于 2020-01-06 02:19:13

问题


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?


回答1:


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,'');
        }
    }



回答2:


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>



回答3:


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");
}


来源:https://stackoverflow.com/questions/16756559/how-to-prevent-spaces-and-full-stops-in-input-field-with-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!