admin管理员组

文章数量:1391981

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. 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. 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.

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. 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. (Example: 27123456789 must bee 0123456789 and not just 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.

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.

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.

I intend for this form to be used mainly on Firefox (66x Quantum versions).

by all means, if my html conflicts or is not patible 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.

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

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. 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. 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.

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. 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. (Example: 27123456789 must bee 0123456789 and not just 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.

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.

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.

I intend for this form to be used mainly on Firefox (66x Quantum versions).

by all means, if my html conflicts or is not patible 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.

<form>
<label>Phone Number</label><br>
<input id="PhoneNumber" type="text" minlength="10" maxlength="10" pattern="[0][0-9]" required>
</form>
Share Improve this question edited Apr 27, 2019 at 22:12 Just A Noobody asked Apr 27, 2019 at 15:40 Just A NoobodyJust A Noobody 111 gold badge1 silver badge3 bronze badges 7
  • 1 developer.mozilla/en-US/docs/Web/HTML/Element/input/tel – NVRM Commented Apr 27, 2019 at 15:46
  • Can you refine your question a bit, so that there is less text, to make it quicker to read and answer. – Alicia Sykes Commented Apr 27, 2019 at 15:46
  • 1 I am confused about "must validate and correct user data immediately": if a user starts typing in an empty input, and types 1, should then immediately the number be prefixed with 9 zeroes!? In my opinion this kind of manipulation should only happen when the user somehow indicates they have finished entering the number they want. – trincot Commented Apr 27, 2019 at 15:49
  • 1 @Cryptopat - Thank you for your suggestion, I will consider the tel input. – Just A Noobody Commented Apr 27, 2019 at 22:19
  • 1 @Alicia - Apologies, I have re edited my post and shortened it as much as (I think) I can. I tend to overthink these things :P – Just A Noobody Commented Apr 27, 2019 at 22:24
 |  Show 2 more ments

2 Answers 2

Reset to default 2

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.

For example

<input type="tel" >

Reference: https://developer.mozilla/en-US/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

[...]

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.

Another contradiction:

Allow the input of numbers only. [...] invalid characters will be ignored/stripped

[...]

Strip international dialing codes from phone numbers, [...] +27123456789 should bee 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.

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>

本文标签: How to autoformat telephone numbers in an HTML text input type field using JavaScriptStack Overflow