2016-10-04 47 views
1

我想是這樣的:我不想讓我的文本框,一個9位數這是格式:123-12-1234或123456789

function k(){ 
    var x = $('#textArea').val(); 
    for (i = 0; i < x.length; i++) 
    { 
    if(x[i].match(/^[0-9]/)) 
    { 
     if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[-]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[-]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/) && x[i+9].match(/^[0-9]/) && x[i+10].match(/^[0-9]/)) 
     { 
     if(x[i+11].match(/^[0-9]/)) 
     { 
      return 'true'; 
     } 
     else 
     { 
      return false; 
     } 
     } 
     else if(x[i+1].match(/^[0-9]/) && x[i+2].match(/^[0-9]/) && x[i+3].match(/^[0-9]/) && x[i+4].match(/^[0-9]/) && x[i+5].match(/^[0-9]/) && x[i+6].match(/^[0-9]/) && x[i+7].match(/^[0-9]/) && x[i+8].match(/^[0-9]/)) 
     { 
     if(x[i+9].match(/^[0-9]/)) 
     { 
      return 'true'; 
     } 
     else 
     { 
      return false; 
     } 
     } 
     else 
     { 
     continue; 
     } 
    } 
    else 
    { 
     continue; 
    } 
    } 
    return 'true'; 
} 
+0

它在相同的答案後點擊鏈接[限制9位數字](http://stackoverflow.com/questions/39726356/how-to-restrict-entering-a-9-dig它-數在-α-數字-文本框) – Anudeep

回答

1

或者乾脆

var x = $('#textArea').val(); 
x = x.replace(/\D+/g,""); //first remove all non-digits from x 
if (x.length <= 8) 
{ 
    return true; 
} 
return false; 

或者,如果你只想讓-digits

var x = $('#textArea').val(); 
var matches = x.match(/[0-9-]/g).length; 
if (!matches || matches.length != x.length) 
{ 
    return false; 
} 
x = x.replace(/\D+/g,""); //first remove all non-digits from x 
if (x.length <= 8) 
{ 
    return true; 
} 
return false; 
0

function myFunc() { 
 
    var patt = new RegExp("\d{3}[\-]\d{2}[\-]\d{4}"); 
 
    var x = document.getElementById("ssn"); 
 
    var res = patt.test(x.value); 
 
    if(!res){ 
 
    x.value = x.value 
 
     .match(/\d*/g).join('') 
 
     .match(/(\d{0,3})(\d{0,2})(\d{0,4})/).slice(1).join('-') 
 
     .replace(/-*$/g, ''); 
 
    } 
 
}
<input class="required-input" id="ssn" type="text" name="ssn" placeholder="123-45-6789" onBlur = "myFunc()">

0

,或者使用純的regexp

以匹配123-45-678和12345678格式:

var x = $('#textArea').val(); 
if (x.match(/^\d{3}-\d{2}-\d{3}$|^\d{8}$/) { 
    return true; 
} else return false; 

匹配任何數目小於9位:

var x = $('#textArea').val(); 
if (x.match(/^(?:\d-?){1,8}$/) { 
    return true; 
} else return false; 
相關問題