gpt4 book ai didi

javascript - 使用纯 JavaScript 将电话号码格式化为用户类型

转载 作者:bug小助手 更新时间:2023-10-28 10:47:28 25 4
gpt4 key购买 nike

我的文档正文中有一个输入字段,我需要在用户键入时对其进行格式化。它应该在区号周围加上括号,然后在三到四位数字之间加上一个破折号。

例如:(123) 456 - 7890

当用户键入时,它应该类似于:

(12
(123)
(123) 456
(123) 456 - 78
(123) 456 - 7890

最佳答案

新的 ES6 答案

您仍然可以使用一些简单的 JavaScript 来做到这一点。

HTML

<input id="phoneNumber" maxlength="16" />

JavaScript (ES6)

const isNumericInput = (event) => {
const key = event.keyCode;
return ((key >= 48 && key <= 57) || // Allow number line
(key >= 96 && key <= 105) // Allow number pad
);
};

const isModifierKey = (event) => {
const key = event.keyCode;
return (event.shiftKey === true || key === 35 || key === 36) || // Allow Shift, Home, End
(key === 8 || key === 9 || key === 13 || key === 46) || // Allow Backspace, Tab, Enter, Delete
(key > 36 && key < 41) || // Allow left, up, right, down
(
// Allow Ctrl/Command + A,C,V,X,Z
(event.ctrlKey === true || event.metaKey === true) &&
(key === 65 || key === 67 || key === 86 || key === 88 || key === 90)
)
};

const enforceFormat = (event) => {
// Input must be of a valid number format or a modifier key, and not longer than ten digits
if(!isNumericInput(event) && !isModifierKey(event)){
event.preventDefault();
}
};

const formatToPhone = (event) => {
if(isModifierKey(event)) {return;}

const input = event.target.value.replace(/\D/g,'').substring(0,10); // First ten digits of input only
const areaCode = input.substring(0,3);
const middle = input.substring(3,6);
const last = input.substring(6,10);

if(input.length > 6){event.target.value = `(${areaCode}) ${middle} - ${last}`;}
else if(input.length > 3){event.target.value = `(${areaCode}) ${middle}`;}
else if(input.length > 0){event.target.value = `(${areaCode}`;}
};

const inputElement = document.getElementById('phoneNumber');
inputElement.addEventListener('keydown',enforceFormat);
inputElement.addEventListener('keyup',formatToPhone);

如果你想摆弄它:
https://jsfiddle.net/rafj3md0/

免责声明:
值得注意的是,如果您尝试修改数字的中间,这会有点奇怪,因为浏览器在设置元素值后处理插入符号位置的方式。解决这个问题是可行的,但需要比我现在更多的时间,而且有一些图书馆可以处理这样的事情。


旧版 ES5 答案

您可以使用快速 javascript 函数来执行此操作。

如果您的 HTML 看起来像:
<input type="text" id="phoneNumber"/>

您的 JavaScript 函数可以是:

// A function to format text to look like a phone number
function phoneFormat(input){
// Strip all characters from the input except digits
input = input.replace(/\D/g,'');

// Trim the remaining input to ten characters, to preserve phone number format
input = input.substring(0,10);

// Based upon the length of the string, we add formatting as necessary
var size = input.length;
if(size == 0){
input = input;
}else if(size < 4){
input = '('+input;
}else if(size < 7){
input = '('+input.substring(0,3)+') '+input.substring(3,6);
}else{
input = '('+input.substring(0,3)+') '+input.substring(3,6)+' - '+input.substring(6,10);
}
return input;
}

当然,您需要一个事件监听器:

document.getElementById('phoneNumber').addEventListener('keyup',function(evt){
var phoneNumber = document.getElementById('phoneNumber');
var charCode = (evt.which) ? evt.which : evt.keyCode;
phoneNumber.value = phoneFormat(phoneNumber.value);
});

除非您可以将电话号码存储为格式化字符串(我不推荐这样做),否则您需要在提交值之前清除非数字字符:
document.getElementById('phoneNumber').value.replace(/\D/g,'');

如果您想通过奖励输入过滤查看此操作,请查看此 fiddle :
http://jsfiddle.net/rm9vg16m/

// Format the phone number as the user types it
document.getElementById('phoneNumber').addEventListener('keyup', function(evt) {
var phoneNumber = document.getElementById('phoneNumber');
var charCode = (evt.which) ? evt.which : evt.keyCode;
phoneNumber.value = phoneFormat(phoneNumber.value);
});

// We need to manually format the phone number on page load
document.getElementById('phoneNumber').value = phoneFormat(document.getElementById('phoneNumber').value);

// A function to determine if the pressed key is an integer
function numberPressed(evt) {
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode < 36 || charCode > 40)) {
return false;
}
return true;
}

// A function to format text to look like a phone number
function phoneFormat(input) {
// Strip all characters from the input except digits
input = input.replace(/\D/g, '');

// Trim the remaining input to ten characters, to preserve phone number format
input = input.substring(0, 10);

// Based upon the length of the string, we add formatting as necessary
var size = input.length;
if (size == 0) {
input = input;
} else if (size < 4) {
input = '(' + input;
} else if (size < 7) {
input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6);
} else {
input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6) + ' - ' + input.substring(6, 10);
}
return input;
}
Enter a phone number here: <input type="text" id="phoneNumber" onkeypress="return numberPressed(event);" />

关于javascript - 使用纯 JavaScript 将电话号码格式化为用户类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30058927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com