2013-05-26 84 views
1

空格和句号在输入字段我有以下不允许空间如何防止使用JavaScript

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

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

回答

1

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

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

感谢这个效果很好。我只是将最后一行更改为t.value = t.value.replace(/ \ s | \ ./ g,''); –

+0

你可以投票这个答案,如果它为你工作 – Tifa

+0

我试过但没有信誉。一旦我得到一个很好的代表,我会回来,并投票 –

相关问题