2015-09-24 75 views
1

我在那裏接受字母,數字和空格的代碼,但我想把它轉換到僅接受字母(AZ,az)和數字(0-9)[SO基本上擺脫了接受空間]。它快把我逼瘋了,我無法弄清楚。並請我想避免則charCode儘可能!只接受在文本框字母和數字使用javascript

function check_username() { 

     //username the user inputted 
     var text_input = $('#text').val(); 
     if (text_input != "") { 
      if (text_input.search(/[^a-zA-Z0-9 ]+/) === -1 && text_input[0] != ' ' && 
        text_input[text_input.length - 1] != ' ' && text_input.length <= 15) { 
       alert("Valid"); 
      } 
      else if (text_input.search(/[^a-zA-Z0-9 ]+/)) { 
       alert("NOT Valid"); 
      } 
     } 
    } 

回答

0

您可以使用.match和正則表達式/^[0-9a-zA-Z]+$/這是一個示例代碼:

function alphanumeric(inputtxt) { 
    var letterNumber = /^[0-9a-zA-Z]+$/; 
    if (inputtxt.match(letterNumber)) { 
    console.log('true'); 
    } else { 
    console.log('false'); 
    } 
} 

alphanumeric('Test Test5'); //False 
alphanumeric('TestTest5'); //True 
相關問題