Skip to content

Instantly share code, notes, and snippets.

@rrmesquita
Created November 22, 2018 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rrmesquita/86405d6fb5fc1aa12e38d7112af1e909 to your computer and use it in GitHub Desktop.
Save rrmesquita/86405d6fb5fc1aa12e38d7112af1e909 to your computer and use it in GitHub Desktop.
Algorithm to validate brazillian phone numbers using jquery-mask-plugin
/**
* Format phone numbers where an ninth digit is optional
*/
(function(){
let phoneInputs = [ '[name="phone"]' ];
let phoneMaskBehavior = function (val) {
return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
};
$.each(phoneInputs, function(index, el) {
if ($(el).length) {
$(el).mask(phoneMaskBehavior, {
onKeyPress: function(val, e, field, options) {
field.mask(phoneMaskBehavior.apply({}, arguments), options);
}
});
}
});
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment