2013-05-26 82 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

我試過但沒有信譽。一旦我得到一個很好的代表,我會回來,並投票 –

相關問題