2014-09-22 63 views
1

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

如果用户输入一个有效的电话号码(正好是10个数字ie.1234567890),那么当用户移动到下一个控件时,输入应该分成3个块作为123-456-7890.otallywise我应该显示错误消息“不是有效的数”。

<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() { 

     } 

     } 
    }; 
}); 
+0

检查了这一点http://stackoverflow.com/a/12728924/3191896 – 2014-09-22 17:33:35

回答

0

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

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(); 
      }); 
     } 
    }; 
}); 

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

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

<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> 

更新fiddle

+0

我想,所以我想在声明中“ngModelCtrl。$ setValidity摆脱硬编码“电话”字段使用该指令在不同的页面/表格/标签(”电话”,参考isValid) ;“。如果我用”phoneformat“(指令名称)替换”telephone“并且它不能按预期工作。请帮助 – user2580179 2014-09-23 14:48:59

+0

该指令专门用于手机。为什么你想让它说出与“电话”不同的错误?如果您想制作类似的指令(例如以验证邮政编码),你有上面的模板,你可以验证,但你需要其他领域的要求...上面的帖子回答您发布的问题。 – Patrick 2014-09-23 17:31:46

+0

示例更新为具有快速5号数字zip:http://jsfiddle.net/4xbv0tgL/18/ - 这显然不是生产zip验证,而是显示如何使用不同指令进行验证的快速示例。为了更进一步,您可以创建一个帮助器函数来为您返回链接函数,您可以在其中传递格式器和解析器函数,但这可能会矫枉过正。 – Patrick 2014-09-23 17:43:06

0

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

+0

你应该提供一个代码片段 – 2014-09-22 17:32:12

+0

谢谢大家。 @Patrick可以避免下面的命令行吗? ie.hard编码字段名(电话)。因为我想利用这个指令在几个形式和这个指令是很常见的所有模块 ngModelCtrl $ setValidity(“电话”,isValid方法)。 – user2580179 2014-09-23 01:01:49

+0

这应该是正确的答案。 +1 – 2015-06-19 15:01:52

0

工作小提琴: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'; 
      } 
     }); 

    } 
}; 

});

0

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>