Javascript 实现 HTML 输入电话掩码 XXX-XXX-XXXX

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/60309429/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:21:51  来源:igfitidea点击:

Implement HTML input phone mask XXX-XXX-XXXX

javascripthtml

提问by FAYSS

I want to have an input for US phone numbers that are auto formatting. In other words, as one is typing the cursor automatically advances to the next section and does not allow more than the mask.

我想输入自动格式化的美国电话号码。换句话说,当一个人正在打字时,光标会自动前进到下一部分,并且不允许超过掩码。

I don't want to use any form submitting. And would like to do it simply with input attributes.

我不想使用任何表单提交。并且想简单地用输入属性来做。

Something like this:

像这样的东西:

<input name="phoneVal" type="text" placeholder="XXX-XXX-XXXX" required>

I've seen this implemented in many sites but I can't figure out how to do it. I've been searching for several hours. I guess I am not putting in the correct search question.

我已经在很多网站上看到过这个实现,但我不知道如何去做。我已经搜索了几个小时。我想我没有输入正确的搜索问题。

回答by Ralph Ritoch

You can use the HTML 5 patternattribute to define a regex to limit the input

您可以使用 HTML 5模式属性定义一个正则表达式来限制输入

<input name="phoneVal" type="text" placeholder="XXX-XXX-XXXX" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" required />

reference: https://www.w3schools.com/tags/att_input_pattern.asp

参考:https: //www.w3schools.com/tags/att_input_pattern.asp

回答by Youssef AbouEgla

Simple form validation can be done using HTML5 that will only notifies user on form submission with incorrect values.

可以使用 HTML5 完成简单的表单验证,该 HTML5 只会在表单提交时通知用户值不正确。

pattern attribute uses regular expression.

模式属性使用正则表达式。

<input name="phoneVal" type="number" min="10" max="10" pattern="RegEx" >

If you are looking for more interactivity and more strict input validationyou will have to use JavaScript.

如果您正在寻找更多的交互性和更严格的输入验证,您将不得不使用 JavaScript。

回答by FAYSS

I finally got it

我终于明白了

var elementExists = document.getElementById("phoneVal");

if (elementExists){
             document.getElementById('_phoneVal').addEventListener('input', function (e) {
              var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
              e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
            });
        }

This only let's user enter values with this format. It automatically fills in 3-3-4 and only allows 10 digits.

这只是让用户使用这种格式输入值。它会自动填写 3-3-4 并且只允许 10 位数字。