Conditional phone mask (with 8 or 9 digits) in Ui Mask. How to do?

Asked

Viewed 10,819 times

4

I’m using the ui.mask to make the masks of inputs. I have a form whose field can receive both a value from a phone and a mobile phone.

I have one currently a input similar to this:

<input type="text" ng-model="cliente.telefone" name="telefone" ui-mask="(99)9?9999-9999" />

With this definition in ui-mask the intention was that if the person filled only 8 digits, the format would look like (33)3333-3333; and if I filled 9, I’d be like (33)99999-9999.

You could do this kind of conditional mask in Ui Mask?

3 answers

2

You can use ui-br-phone-number library angular-input-masks, for example:

<input type="text" ui-br-phone-number  />

2

The component should treat this case as well as other similar plugins. However, I have created a directive that solves your problem. Follow below:

// no Controller

$scope.cliente = { telefone: 0 }
$scope.phoneMask = "(99) 9999-9999";

//HTML

<input type='text' ng-model='cliente.telefone' ui-mask="{{phoneMask}}" mask-change="phoneMask" />

// Diretiva

app.directive('maskChange', function() {
    return {
        restrict: 'A',
        scope: {
            maskChange: "=",
        },
        require: '?ngModel',
        link: function(scope, elem, attrs, ngModel) {

            var novoTel, flag = false, val;

            elem.off('keyup');
            elem.on('keyup', function(ev) {

                if (/^\d+$/.test(ev.key) || ev.key == 'Backspace' || ev.key == 'Delete') {

                    novoTel = String(ngModel.$viewValue).replace(/[\(\)\_\-/\s]/g, '')

                    if (novoTel.length == 10 && !flag) {
                        flag = true;
                        scope.maskChange = "(99) 9999-9999";
                        scope.$apply();
                    } else if (novoTel.length == 10 && flag) {
                        flag = false;
                        scope.maskChange = "(99) 9?9999-9999";

                        scope.$apply();
                        ngModel.$viewValue += ev.key
                        ngModel.$render();

                    } else if (novoTel.length < 10) {
                        flag = false;
                    }
                }
            })
        }

    };
})

1

Like alternative suggestion you can use the https://github.com/assisrafael/angular-input-masks, lower the angular-input-masks-standalone.min.js via https://github.com/assisrafael/angular-input-masks/releases and add to your page like this:

<script src="angular-input-masks-standalone.min.js"></script>

If you use NPM to install the dependencies then install via command line, thus:

npm install --save angular-input-masks

Should add so:

angular.module('demo', ['ui.utils.masks'])

And in the input should look like this:

<input type="text" ng-model="cliente.telefone" name="telefone" ui-br-phone-number>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.