2015-10-15 61 views
2

我想允許輸入具有這些組合的手機號碼(7或8或9)。jQuery允許手機號碼的具體號碼

我只限制字母(只允許數字),但如何限制其他的數字比7或8或9

$(document).on('keypress', '.mobnum', function (e) { 
     //if the letter is not digit then display error and don't type anything 
     if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { 
      if (e.which == 118){ 
      return true; 
      }else{ 
      return false; 
      } 
     } 
    }); 
+1

您可以使用正則表達式承擔,即像'^ [789] \ d印度數{9} $' – Satpal

+1

thanks..but如何按鍵進行整合 – vishnu

回答

2

使用以下函數來restict移動號碼

$(document).on('keypress', '.mobnum', function (e) { 
    var mobnum="987654321"; 
    if (mobnum === ''|| mobnum === 'null'|| mobnum === null || phonenumber(mobnum)=== false) 
    { 
    } 
    else 
    { 
    your operations 
    } 
}); 
    function phonenumber(mobnum) { 
    var pattern = new RegExp(/^[789]\d{9}$/i); 
    return pattern.test(mobnum); 
    }; 
1

您可以使用charAt()方法返回字符串中指定索引處的字符。

第一個字符的索引是0,第二個字符是1,依此類推。

if (!(contactNumber.charAt(0) == "9" || contactNumber.charAt(0) == "8" || contactNumber.charAt(0) == "7")) { 
      //DO THE VALIDATION 
} 
0

我使用此代碼,只允許數字:

// allow only numbers 
var ctrlAltShift = false; 
$(document).keydown(function(e) { 
    if (e.keyCode >= 16 && e.keyCode <= 18) ctrlAltShift = true; 
}).keyup(function(e) { 
    if (e.keyCode >= 16 && e.keyCode <= 18) ctrlAltShift = false; 
}); 
$(document).on('keydown', '.mobnum', function(e) { 
    if( 
     (
      !ctrlAltShift && (
       (e.keyCode >= 48 && e.keyCode <= 57) || /* allow Digit 0 - 9 */ 
       (e.keyCode >= 96 && e.keyCode <= 105) || /* allow Numpad 0 - 9 */ 
       ($.inArray(e.keyCode, [8, 9, 27, 35, 36, 37, 39, 46]) !== -1) /* allow backspace, tab, esc, end, home, arrow left, arrow right, del */ 
      ) 
     ) || 
      ctrlAltShift && e.keyCode == 9 /* allow ctrl (+ shift) + tab */ 
    ) { 
     return; 
    } 
    else { 
     e.preventDefault(); 
    }   
});