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

3

I'm using ui.mask to make the input masks. I have a form whose field can receive either a value from a phone or a cell phone.

I currently have a input similar to this:

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

With this setting in ui-mask the intention was that if the person filled only 8 digits, the formatting would be (33)3333-3333 ; and, if you filled 9, it would look like (33)99999-9999 .

Would you like to make this kind of conditional mask on Ui Mask?

    
asked by anonymous 24.01.2017 / 17:22

3 answers

2

The component should handle this case, as well as other similar plugins. However, I've 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;
                    }
                }
            })
        }

    };
})
    
25.01.2017 / 13:25
1

As alternative suggestion you can use link , download angular-input-masks-standalone.min.js via link and add it 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 the command line, like this:

npm install --save angular-input-masks

It should add like this:

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

And in input should look like this:

<input type="text" ng-model="cliente.telefone" name="telefone" ui-br-phone-number>
    
17.11.2017 / 20:15
1

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

<input type="text" ui-br-phone-number  />
    
17.11.2017 / 19:53