Skip to content

Instantly share code, notes, and snippets.

@Fawers
Created April 6, 2016 16:37
Show Gist options
  • Save Fawers/66a042ff987a2150171af8f39415351d to your computer and use it in GitHub Desktop.
Save Fawers/66a042ff987a2150171af8f39415351d to your computer and use it in GitHub Desktop.
Phone mask for Brazilian phone numbers
/* REQUIRES jQUERY */
// Mask for the area code
var patternDDD = /^(\d\d)(.+)/,
// Mask for the de facto number
patternPhone = /^(\d\d)(\d)?(\d{4})(\d{4})$/;
// Sometimes the phone number (especially mobile phones) may have an
// additional digit; hence the optional \d in the second group.
// Change the id below to your id, or class, or whatever.
// works better (i.e., only tested) with an input[type=text]
// by the way, this is the only part that requires jQuery...
// maybe you don't really need jQuery.
$('#id_of_your_phone_number_text_input').on('input change', function () {
var value = this.value,
stripped = value.replace(/\D/g, '').slice(0, 11), // get numeric characters only
string,
match;
// Matching the entire phone number
if (patternPhone.test(stripped)) {
match = stripped.match(patternPhone).slice(1);
// if the additional digit is present, place one additional %s
string = match[1] ? '(%s) %s %s-%s' : '(%s) %s-%s';
// I miss a good 'format' function for JS.
match.forEach(function (m) {
if (m) string = string.replace('%s', m);
});
this.value = string.trim();
}
// matching only the area code
else if (patternDDD.test(stripped)) {
match = stripped.match(patternDDD);
string = '(' + match[1] + ') ' + match[2];
this.value = string.trim();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment