Hikari Hikari - 1 year ago 172
jQuery Question

JavaScript mask for Brasil phone number

Currently I'm using jquery.maskedinput for verious mask formats, but it's not working for phone numbers.

In Brasil we used to have all numbers in the format (99)9999-9999. But lately, in a few cities, cell phones are using (99)99999-9999, while their normal phones and the rest of the country remain (99)9999-9999.

jquery.maskedinput seems to not support 2 formats on the same input where a character in the middle of the string may or may not be present. As I can see in its documentation, I could have (99)9999-9999 and (99)9999-99999, but that would confuse users.

Is there any other mask plugin/framework that allows me to validate both (99)9999-9999 and (99)99999-9999?

Edit: I created a full test using harry and Dmitrii solutions: http://jsfiddle.net/NSd6g/


I'm gonna wait a bit more to see if I can find an even better solution. The perfect one wouldn't require the red message, second group would have 4 digits by default. And, if third group would get a fifth digit, only then second group would get its fifth space, moving third group's first digit into second group's fifth. lol kinda hard to understand, sorry!

Answer Source

You could achieve this using jquery.inputmask as simple as:

jQuery(function($) {

Try this demo.

To skip the optional part while typing into the input you need to type space or the char following the optional part in the mask (hyphen in this case).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download