I have the following rules for phone number data entry:
- For USA phones, it must follow format (999) 999-9999
- For non-USA phones, it must start with a + followed by any combination of digits, hyphens, and spaces (basically, much less strict than the USA format)
I have regex validation that ensures that the entered phone number matches these rules. I want to use a phone format mask that follows the above rules.
For example, the simple case of just allowing the specific USA format, I can do:
<label for="phone">Enter Phone Number:</label>
<input type="text" id="phone" name="phone">
<script type="text/javascript">
$(function () {
$('.usa-phone').mask("(999) 999-9999");
});
</script>
This would display something like this in the textbox when the user clicks to focus the phone textbox:
(___) ___-____
But how do I then allow for international phones that start with "+" sign in the same input field?
For example +99 (99) 9999-9999
.
There are several solutions to this, including having the user picking from a drop-down-list as to which country they are in, so you can setup the format accordingly. A second way would be to intercept the users individual keystrokes and then change the format as you se +44 or +39 to represent the UK or Italian number format.
There are several packages out there that implements it, and since there are 100's of countries many with more than one or two format in each country, you probably should not try to implement this yourself,but instead use one of those packages
I think I have used this one here: https://github.com/albeebe/phoneformat.js in an earlier project.
Since you are looking for a Jquery solution, the stripe library looks promising https://github.com/stripe/jquery.mobilePhoneNumber
If you are OK building a bit of code yourself you may be able to combine the keyboard processing explained here How to change Phone number format in input as you type? with the core code from either of the other libs
So, to grossly over-simplify the logic, you would dynamically change the format of the filed based on inputs in a keyup event, like