2017-07-28 85 views
2

進出口使用的jQuery的姓名驗證我已經試過這將在下文不允許空格作爲第一個字符,使用jquery

$("#contactname").keypress(function(e) { 
    if(e.which < 97 /* a */ || e.which > 122 && (e.which < 65 || e.which > 90)) { 
     e.preventDefault(); 
    }   
}); 

給上面的代碼工作正常,只允許字母代碼,只允許字母和不允許數字,但它不允許空間。所以我想要的是它應該只允許字母(小寫字母和大寫字母),那麼它不應該允許數字和特殊字符,也可以接受空間,除了作爲第一個字符請告訴我如何限制複製粘貼。

回答

1

你可以使用HTML5屬性pattern?請參閱​​瞭解更多信息。

使用正則表達式^[a-zA-Z][\sa-zA-Z]*似乎涵蓋了您的要求。

因此,像:

<div>Username:</div> 
 
<input type="text" pattern="^[a-zA-Z][\sa-zA-Z]*" title="Can use upper and lower letters, and spaces but must not start with a space" />

1

你應該試試這個

$("#contactname").keypress(function(event){ 
     var inputValue = event.charCode; 
     if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)){ 
      event.preventDefault(); 
     } 
}); 
+0

但在開始其預留空間 – Vinothini

0

我終於拿到了這個問題

$("#contactname").keypress(function(e) { 
     if (e.which === 32 && !this.value.length) { 
      e.preventDefault(); 
     } 
     var inputValue = event.charCode; 
     if(!(inputValue >= 65 && inputValue <= 120) && (inputValue != 32 && inputValue != 0)){ 
      event.preventDefault(); 
     }   
    }); 

此代碼工作的罰款,我的確切需要的解決方案

相關問題