Only Alphanumeric JavaScript No Special Character

  1. <asp:TextBox ID="GroupCode" runat="server" MaxLength="50" onkeypress="return noAlphabets(event)" ></asp:TextBox>  
  2. function noAlphabets(e) 
  3. {    
  4.         var regex = new RegExp("[a-zA-Z0-9]");    
  5.         var key = e.keyCode || e.which;    
  6.         key = String.fromCharCode(key);    
  7.         if (!regex.test(key)) 
  8.          {    
  9.             e.returnValue = false;    
  10.             if (e.preventDefault)
  11.             {    
  12.                 e.preventDefault();    
  13.             }    
  14.          }   
  15. }    
In this function we can only enter alphanumeric no special character enter in this textbox. If we want any specific special character to enter in the textbox, then we just mention in the last of regular expression condition.
  1. function noAlphabets(e) 
  2. {  
  3.         var regex = new RegExp("[a-zA-Z0-9@ ]");  
  4.         var key = e.keyCode || e.which;  
  5.         key = String.fromCharCode(key);  
  6.         if (!regex.test(key)) 
  7.          {  
  8.             e.returnValue = false;  
  9.             if (e.preventDefault)    
  10.             {  
  11.                 e.preventDefault();  
  12.             }  
  13.         }  
  14. }