Nic*_*rie 1 javascript regex jquery phone-number
我在HTML表单中有一个需要格式化的电话字段
(555)555-5555
这是领域:
<input type="tel" id="phone" name="phone" placeholder="(555) 555-5555" autocomplete="off" maxlength="14" required="required">
Run Code Online (Sandbox Code Playgroud)
一些要求:
如何使用jQuery/Javascript将这种类型的需求应用于这些需求?
我拼凑了其他相关问题的答案,以及我自己的代码,并提出了似乎运行良好的解决方案:
// Phone formatting: (555) 555-5555
$("#phone").on("keyup paste", function() {
// Remove invalid chars from the input
var input = this.value.replace(/[^0-9\(\)\s\-]/g, "");
var inputlen = input.length;
// Get just the numbers in the input
var numbers = this.value.replace(/\D/g,'');
var numberslen = numbers.length;
// Value to store the masked input
var newval = "";
// Loop through the existing numbers and apply the mask
for(var i=0;i<numberslen;i++){
if(i==0) newval="("+numbers[i];
else if(i==3) newval+=") "+numbers[i];
else if(i==6) newval+="-"+numbers[i];
else newval+=numbers[i];
}
// Re-add the non-digit characters to the end of the input that the user entered and that match the mask.
if(inputlen>=1&&numberslen==0&&input[0]=="(") newval="(";
else if(inputlen>=6&&numberslen==3&&input[4]==")"&&input[5]==" ") newval+=") ";
else if(inputlen>=5&&numberslen==3&&input[4]==")") newval+=")";
else if(inputlen>=6&&numberslen==3&&input[5]==" ") newval+=" ";
else if(inputlen>=10&&numberslen==6&&input[9]=="-") newval+="-";
$(this).val(newval.substring(0,14));
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3007 次 |
| 最近记录: |