1

How can I mask a HTML input text with a mask for phone number?

Here in Brazil, in some states, the number format can change. For example:

(dd)xxxx-xxxx this is the default number format, where dd is the state code, and the x's are the numbers.

BUT, in some states, the number nine is added to the phone number, like this: (dd)9xxxx-xxxx. (let's call it "new format")

the var dd isn't important, what I want to do is when the user type the new format, the hyphen automatically appears after the 4th X.

3 Answers3

1

When the users start entering the phone number, you could have a regex such as ^(\d{2})9 and regex match the string to see if the hyphen needs to be added at a different place.

Josh
  • 334
  • 1
  • 17
0

You could use something like formatter.js to do the job for you!
I have not tried it, but the demos look quite solid.

grilly
  • 450
  • 4
  • 11
  • That's nice, thanks for this information, it will help me later, but how can I set the mask to change the hyphen when my phone number is bigger than 8 digits? Because when the number has 8 digits, the hyphen must be centered (xxxx-xxxx). When I have 9 digits, the hyphen must be after the 4th digit and the number nine must be add before the fist number (9xxxx-xxxx). – Felipe Leal Feb 25 '15 at 18:19
0

Try using two inputs with different masking (8 digit & 9 digit respectively) and switch them based on the state selected in the form.

segaurav
  • 217
  • 2
  • 5