简体   繁体   English

如何使用JavaScript自动格式化HTML文本输入类型字段中的电话号码?

[英]How to auto-format telephone numbers in an HTML text input type field using JavaScript?

I need a solution for the following 3-part challenge I am facing. 我需要解决以下三个挑战。

On a web page form,I have an input type = “text” field where it requires the user to input a 10 digit only telephone number. 在网页表单上,我有一个输入类型=“文本”字段,要求用户输入仅10位数字的电话号码。 I need the field to be able to do the following as and when the user inputs the data (either enters the data manually via typing from the keyboard or, copying and pasting data): 当用户输入数据时,我需要该字段能够执行以下操作(通过键盘输入或复制和粘贴数据来手动输入数据):

Allow the input of 10 numbers only. 只允许输入10个数字。 Example: when the user inputs a phone number, and accidentally inserts a letter, a symbol character or the space key in the text field, these invalid characters will be ignored/stripped. 示例:当用户输入电话号码,并在文本字段中意外插入字母,符号字符或空格键时,这些无效字符将被忽略/剥离。 Example: User inputs q01234 56789p, only 0123456789 should be taken into the field. 示例:用户输入q01234 56789p,该字段只能输入0123456789。

If 27 is detected at the beginning of the telephone number, it must convert it to a 0 but, must still be able to capture the last digit. 如果在电话号码的开头检测到27,则必须将其转换为0,但仍必须能够捕获最后一位数字。 This is mainly for when the user pastes the data containing a 27 at the beginning, it must capture the entire number following the 27 as well and not omit the last digit, as phone numbers beginning with 27 will make the phone number 11 digits in total, therefore exceeding the 10 digit limit by 1 digit. 这主要用于用户在开头粘贴包含27的数据时,必须同时捕获27后面的整数,并且不能省略最后一位,因为以27开头的电话号码会使电话号码总计11位数,因此超出10位数字限制1位数字。 (Example: 27123456789 must become 0123456789 and not just 012345678). (例如:27123456789必须成为0123456789,而不仅仅是012345678)。 Is there a way this can be done as the user pastes the data into the field instead of waiting for the user to loose focus on the field first or can this be done even if the user looses focus on the field? 当用户将数据粘贴到字段中时,是否有办法做到这一点,而不是等待用户首先将焦点放到该字段上?或者即使用户将精力放在该字段上,也可以这样做吗? I ask as I am concerned about the limit not inserting the final digit from a copied value containing 11 digit due to it starting with a 27. 我问我,因为我担心限制不会从复制的包含11位数字的值中插入最后一位数字,因为它以27开头。

All of the above conditions must validate and correct user data, as the user attempts to go onto the next input field by either pressing enter, tab or clicking on the next input field. 当用户尝试通过按Enter,Tab键或单击下一个输入字段进入下一个输入字段时,上述所有条件都必须验证并更正用户数据。

The intended use of this form is for the user who will either be entering data on the fly or copying and pasting data from various, external logs that have either omitted the leading zero or included the +27 international dialing code. 此表单的预期用途是给用户输入数据的时间,或者是从各种外部日志中复制和粘贴数据的用户,这些外部日志要么省略了前导零,要么包括了+27国际拨号代码。

I intend for this form to be used mainly on Firefox (66x Quantum versions). 我打算将此表格主要用于Firefox(66x Quantum版本)上。

by all means, if my html conflicts or is not compatible with the necessary JS code to pull this off, I don't mind changing it, as long as it remains a text box and does not need to be changed into a “text field” or a “number” input type. 无论如何,如果我的html发生冲突或与实现该目标的必要JS代码不兼容,那么我不介意对其进行更改,只要它仍然是文本框并且不需要更改为“文本字段”即可”或“数字”输入类型。

<form>
<label>Phone Number</label><br>
<input id="PhoneNumber" type="text" minlength="10" maxlength="10" pattern="[0][0-9]" required>
</form>

There is actually an input type of tel, which will save you a lot of hassle. 实际上有电话的输入类型,它将为您节省很多麻烦。 Using <input type="tel" ... would be the correct approach, and it also allows you to specify a regex to validate the phone number to your specification, using the pattern attribute. 使用<input type="tel" ...是正确的方法,它还允许您使用pattern属性指定一个正则表达式来验证电话号码是否符合规范。

For example 例如

<input type="tel" >

Reference: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/tel 参考: https : //developer.mozilla.org/zh-CN/docs/Web/HTML/Element/input/tel

It is worth noting, that you will still need server-side validation, of course. 值得注意的是,您当然仍然需要服务器端验证。 You should use the same regex on both client, and server. 您应该在客户端和服务器上使用相同的正则表达式。

This is widely supported now, but if your worried, see this answer 现在已广泛支持此功能,但如果您担心,请参阅此答案

First, I would advise against removing characters immediately, as it can be counter-intuitive for the user: you don't want them to think their keyboard is broke. 首先,我建议不要立即删除字符,因为这对于用户而言可能是违反直觉的:您不希望他们认为自己的键盘坏了。

Secondly, some of your requirements are contradictory. 其次,您的某些要求是矛盾的。 Two examples: 两个例子:

the input must still append a zero to the beginning of that phone number to make it 10 digits in total 输入仍必须在该电话号码的开头加上一个零,以使其总数达到10位

[...] [...]

All of the above conditions must validate and correct user data immediately, as and when the user inputs the data 当用户输入数据时,上述所有条件必须立即验证并更正用户数据

This would mean that if the user starts typing in the empty input field, and types a "1", the rule should kick in immediately and make that phone number 10 digits in total. 这意味着,如果用户开始在空的输入字段中键入并键入“ 1”,则规则应立即生效,并使该电话号码总计10位数。

Another contradiction: 另一个矛盾:

Allow the input of numbers only. 只允许输入数字。 [...] invalid characters will be ignored/stripped [...]无效字符将被忽略/剥离

[...] [...]

Strip international dialing codes from phone numbers, [...] +27123456789 should become 0123456789 从电话号码中删除国际拨号代码,[+] 12123456789应该变成0123456789

But if the user can only type digits, then they would never be able to enter +27: already when they type the "+", it would be stripped. 但是,如果用户只能输入数字,那么他们将永远无法输入+27:已经输入“ +”时,它将被删除。

This can of course not be the intended behaviour. 当然,这不是预期的行为。 So at least some rules should only be applied when the user somehow indicates they have finished entering the phone number. 因此,至少应在用户以某种方式指示他们已完成输入电话号码时应用某些规则。 This can be done when they move the selection to a next input field. 当他们将选择内容移至下一个输入字段时,可以完成此操作。

Here is an implementation where characters other than digits and "+" are ignored/stripped immediately, and a "+" can only be entered as the left-most character. 这是一种实现,其中数字和“ +”以外的其他字符将被立即忽略/剥离,并且“ +”只能作为最左边的字符输入。

The removal of the international dial code, and the padding with zero, will only be applied when the focus changes: 仅当焦点更改时才应用国际拨号代码的删除以及零填充。

 const el = document.querySelector("#PhoneNumber"); const littleClean = input => input.replace(/(\\d)\\D+|^[^\\d+]/g, "$1") .slice(0, 12); const bigClean = input => !input ? "" : input.replace(/^\\+(27)?/, "") .padStart(10, "0") .slice(0, 10); const format = clean => { const [i, j] = [el.selectionStart, el.selectionEnd].map(i => clean(el.value.slice(0, i)).length ); el.value = clean(el.value); el.setSelectionRange(i, j); }; el.addEventListener("input", () => format(littleClean)); el.addEventListener("focus", () => format(bigClean)); el.addEventListener("blur", () => format(bigClean)); 
 <form> <label>Phone Number<br> <input id="PhoneNumber" type="tel" minlength="10" required></label><br> <label>Name<br> <input id="Name" type="text" required></label><br> </form> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 自动格式化 html 输入类型电话 - Auto-format html input type tel 使用 Javascript 自动格式化驾照? - Auto-format Driver's License using Javascript? 如何在键入和/或粘贴文本时清理(仅限数字和连字符)和自动格式化(插入连字符和前导零)文本输入值? - How to sanitize (digits and hyphen only) and auto-format (hyphen and leading zeros insertion) a text input value while typing and/or pasting text? 如何使用 Angular 自动格式化电话号码 - How to auto-format phone number using Angular 在 RStudio Server 中自动格式化 JavaScript 代码 - Auto-format javascript code in RStudio Server 在 FOCUS 上使用 Javascript 的 Auto Dash(用于电话号码格式) - Auto Dash using Javascript on FOCUS (for a telephone number format) 如何使用 JavaScript 显示 html 输入:.html(&#39; &lt; input type=&quot;text&quot; /&gt;&#39;) - How to display a html input using JavaScript : .html(' < input type="text" />') 使用jQuery插件自动格式化结构化数据(手机,日期)(或者使用vanilla JavaScript失败) - Auto-format structured data (phone, date) using jQuery plugin (or failing that vanilla JavaScript) 自动格式化作为用户类型输入的信用卡号 - Auto-format credit card number input as user types 如何使用JavaScript阻止文本字段中的任何类型的输入? - How to prevent any type of input in text field using JavaScript?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM