2012-09-11 58 views
0

我有一個用於驗證用戶名的文本框。但是我想限制特殊字符在他們嘗試輸入或嘗試粘貼文字時(以及特殊字符)。我怎麼能通過js來做到這一點。已經編寫了一個代碼,但只有我可以在輸入時限制那些特殊字符,但是當我在該文本框上粘貼一些單詞時,無法限制這些字符。我的代碼是這樣的:避免鍵入一些特殊字符

<input type="text" name="bus_uname" id="bus_uname" class="reg-line-input" 
    value="<?php echo ($back_uname!='')?$back_uname:'Business Username';?>" 
    onblur="if(this.value=='') this.value='Business Username'" 
    onFocus="if(this.value=='Business Username') this.value='';" 
    onkeypress="return usernameonly(event, false)" /> 

和JS

function usernameonly(e, decimal) { 
    var key; 
    var keychar; 

    if (window.event) { 
     key = window.event.keyCode; 
    } 
    else if (e) { 
     key = e.which; 
    } 
    else { 
     return true; 
    } 
    keychar = String.fromCharCode(key); 

    if ((key==null) || (key==0) || (key==8) || (key==9) || (key==13) || (key==27)) { 
     return true; 
    } 
    else if ((("[email protected]#$%^&*()_+-=?/.><,';:").indexOf(keychar) > -1)) { 
     return false; 
    } 
    //else 
    // return false; 
} 

請幫助如何解決這個問題。

+0

看到這可能是幫助你http://stackoverflow.com/questions/6035071/intercept-paste-event-in-javascript – Hkachhia

+0

也許替換整個字中的字符是一個更好的解決方案;) – Snicksie

回答

0
<input type="text" name="bus_uname" id="bus_uname" class="reg-line-input" value="<?php echo ($back_uname!='')?$back_uname:'Business Username';?>" onblur="if(this.value=='') this.value='Business Username'" onFocus="if(this.value=='Business Username') this.value='';" onkeypress="return usernameonly(event, false)" onpaste="return false" /> 

我添加onpaste="return false",使您的用戶將無法粘貼,他們必須鍵入的用戶名。

+0

非常感謝。它的工作正常。 – sundar