使用angularjs的电话格式的自定义指令

Custom directive for telephone format using angularjs

本文关键字:自定义 指令 格式 电话 angularjs 使用      更新时间:2023-09-26

我正在尝试使用angularjs为美国电话号码编写自定义指令,并且需要将字段的数据类型保留为整数。这是jsfiddle指令,需要帮助才能完成该指令。

如果用户输入了一个有效的电话号码(正好是10个号码,即123567890),那么当用户移动到下一个控件时,输入应分为3块,即123-456-7890。因此,我应显示错误消息"不是有效号码"。

<div ng-app="myApp" ng-controller="myCtrl">
<form name="myForm">
    <input type="text" ng-model="telephone" phoneformat  name="input1" />
     <span class="error" ng-show="myForm.input1.$error.telephone">Numbers only!</span>
    <span class="error" ng-show="myForm.input1.$error.telephone">Exact 10 Numbers only!</span>
</form>
</div>
var myApp = angular.module("myApp", []);
var myCtrl = myApp.controller("myCtrl",["$scope", function($scope) {
$scope.telephone = "1234567890";
}]);
 myApp.directive("phoneformat", function () {
  return {
    restrict: "A",
    require: "ngModel",
    link: function (scope, element, attr, ngModelCtrl) {
        var phoneformat = function () {
        }
      }
    };
 });

看起来您想要利用表单的$error属性来驱动验证。要做到这一点,您需要在ngModelCtrl中调用$setValidity,这是您在指令中所要求的:

var myApp = angular.module("myApp", []);
var myCtrl = myApp.controller("myCtrl",["$scope", function($scope) {
    $scope.telephone = "1234567890";
}]);
myApp.directive("phoneformat", function () {
    return {
        restrict: "A",
        require: "ngModel",
        link: function (scope, element, attr, ngModelCtrl) {
            //Parsing is performed from angular from view to model (e.g. update input box)
            //Sounds like you just want the number without the hyphens, so take them out with replace
            var phoneParse = function (value) {
                var numbers = value && value.replace(/-/g, "");
                if (/^'d{10}$/.test(numbers)) {
                    return numbers;
                }
                return undefined;
            }
            //Formatting is done from view to model (e.g. when you set $scope.telephone)
            //Function to insert hyphens if 10 digits were entered.
            var phoneFormat = function (value) {
                var numbers = value && value.replace(/-/g,"");
                var matches = numbers && numbers.match(/^('d{3})('d{3})('d{4})$/);
                if (matches) {
                    return matches[1] + "-" + matches[2] + "-" + matches[3];
                }
                return undefined;
            }
           //Add these functions to the formatter and parser pipelines
           ngModelCtrl.$parsers.push(phoneParse);
           ngModelCtrl.$formatters.push(phoneFormat);
           //Since you want to update the error message on blur, call $setValidity on blur
           element.bind("blur", function () {
                var value = phoneFormat(element.val());
                var isValid = !!value;
                if (isValid) {
                    ngModelCtrl.$setViewValue(value);
                    ngModelCtrl.$render();
                }
                ngModelCtrl.$setValidity("telephone", isValid);
                //call scope.$apply() since blur event happens "outside of angular"
                scope.$apply();
            });
        }
    };
});

工作小提琴。这只是演示ngModel中使用的解析器和格式化程序管道以及用于填充$error字段的$setValidity的一种快速方法。

更新:要在多部手机之间使用相同的手机验证,请使用带有$error的表单。请注意,每个输入都有一个与myForm(表单名称)一起使用的唯一名称。两者都使用$error.电话:

<form name="myForm">
    Mobile Phone:
    <input type="text" ng-model="mobilephone" phoneformat name="mobilephone" />
    <span class="error" ng-show="myForm.mobilephone.$error.telephone">
       Exact 10 Numbers only!
    </span>
    <br />
    Home Phone:
    <input type="text" ng-model="homephone" phoneformat  name="homephone" />
    <span class="error" ng-show="myForm.homephone.$error.telephone">
        Exact 10 Numbers only!
    </span>
</form>

更新的小提琴。

您可能想要使用http://angular-ui.github.io/ui-utils/Mask指令。

工作Fiddle:http://jsfiddle.net/HB7LU/6581/

myApp.directive("phoneFormat", function () {
return {
    restrict: "A",
    link: function (scope, element, attr) {
        element.bind('change', function() {
            if ( this.value.length === 10 ) {
               var number = this.value;
               this.value = number.substring(0,3) + '-' + number.substring(3,6) + '-' + number.substring(6,10)
            }
            else {
                document.querySelector('.helpblock').innerHTML = 'error in formatting';
            }
        });
    }
};

});

Iv'e扩展了您原来的小提琴。结果如下:http://jsfiddle.net/10k58awt/

您可以在表单提交上找到splittedNumber数组(包含3部分数字)

js:

var myApp = angular.module("myApp", []);
var myCtrl = myApp.controller("myCtrl", ["$scope", function ($scope) {
    $scope.telephone = "1234567890";
    $scope.submit = function () {
        var splittedNumber = [$scope.telephone.substring(0, 3), $scope.telephone.substring(3, 6), $scope.telephone.substring(6, 10)];
        // Do something with splitted number
        console.log(splittedNumber);
    };
}]);
myApp.directive("phoneformat", function () {
    return {
        restrict: "A",
        require: "ngModel",
        link: function (scope, elm, attrs, ctrl) {
            ctrl.$parsers.unshift(function (phoneInput) {
                phoneInput = phoneInput.trim();
                if (phoneInput && phoneInput.length == 10 && !isNaN(phoneInput)) {
                    ctrl.$setValidity('phoneformat', true);
                    return phoneInput;
                } else {
                    ctrl.$setValidity('phoneformat', false);
                    return undefined;
                }
            });
        }
    };
});

html:

<div ng-app="myApp" ng-controller="myCtrl">
    <form name="myForm" novalidate ng-submit="myForm.$valid && submit()">
        <input type="text" ng-model="telephone" phoneformat name="input1" /> <span class="error" ng-show="myForm.input1.$error.phoneformat">Invalid US Phone number!</span>
        <div>
            <button class="btn btn-primary" type="submit" ng-class="{'disabled': !myForm.$valid}">submit</button>
        </div>
    </form>
</div>