7

Im using jquery masked input plugin and need to have a phone field with the following format:

1 (222) - 000 - 1114

my code looks like this:

$("#myPhone").mask("9 (999) - 999 - 9999");

now i cant seem to get it to work to make the first digit optional but the rest mandatory. So the following numbers are valid:

1 (222) - 000 - 1114
  (222) - 000 - 1114

and the following numbers are invalid

1 (222) - 000 - 11
  (222) - 00  - 0011

using "?9 (999) - 999- 9999" will not work since it makes the whole thing optional

If this cant be done in masked can someone help me out with regular expression to achieve this?

GGio
  • 7,563
  • 11
  • 44
  • 81

2 Answers2

18

Try this:

$.mask.definitions['~'] = '([0-9] )?';
$("#myPhone").mask("~(999) - 999 - 9999");
vcampitelli
  • 3,168
  • 1
  • 12
  • 13
  • 1
    worked perfectly, thanks alot. One problem though the first digit is not strictly digit, if i type letter it types in letter – GGio Mar 12 '13 at 20:24
  • This is not a good solution. This fix the problem if you start typing on the input. But if you recovery the data from the database (for example) and apply the mask your input are blank. – MarceloBarbosa May 16 '16 at 20:10
  • Yeah how do you make sure the first digit is exactly a digit? In my case I want know if it is a + – Mukus Feb 25 '20 at 04:40
0

It is not perfect, but you can use number or whitespace:

$.mask.definitions['~'] = '[0-9 ]';
$("#myPhone").mask("~(999) - 999 - 9999");
Sertage
  • 3,123
  • 1
  • 19
  • 26