简体   繁体   中英

Implement HTML input phone mask XXX-XXX-XXXX

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.

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

<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

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

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 validation you will have to use JavaScript.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM