Angular 1.4 version of google-libphonenumber

1.3k views Asked by At

I am trying to use google-libphonenumber for phone number validation in my angular 1.4 based application.

https://github.com/ruimarinho/google-libphonenumber

Its is working as expected if i do this in my node server code.

But, I would like to have this validation in my client side validation directive.

I am not sure which module to inject in my directive so as to use this in the client side. I tried to inject "PhoneNumberUtil", "google-libphonenumber", nothing works.

Is there any angular 1.4 example for this?

Thanks

1

There are 1 answers

0
Pavel Bely On

Since the library you mentioned is not an Angular module you can't inject it as a dependency into your directive.

However you can require or import it in the directive script like that:

const PhoneNumber = require('google-libphonenumber').PhoneNumberUtil.getInstance();

const PhoneNumberDirective = function ($log) {
    'ngInject';

    return {
        restrict: 'A',
        require: '?ngModel',
        scope: {
            countryCode: '=',
            nonFormatted: '=?',
        },
        link(scope, element, attrs, ctrl) {
            function validator(value) {
                let isValidForRegion = false;
                try {
                    const number = PhoneNumber.parse(value, scope.countryCode);
                    isValidForRegion = PhoneNumber.isPossibleNumber(number);
                } catch (err) {
                    $log.debug(err);
                }
                const valid = ctrl.$isEmpty(value) || isValidForRegion;
                ctrl.$setValidity('phoneNumber', valid);
                return value;
            }

            ctrl.$formatters.push(validator);
            ctrl.$parsers.push(validator);
        },
    };
};

export default PhoneNumberDirective;

Also check out https://github.com/cwill747/angular-libphonenumber

maybe it will work for you.