使用AngularJs仅允许文本框中的字符

时间:2013-02-02 18:54:17

标签: javascript javascript-events angularjs angularjs-directive

我只想以这种方式验证项目中的文本框,以便用户无法输入除字符之外的任何值。

1 个答案:

答案 0 :(得分:2)

<强>的hackish?方式,$在你的控制器中观察ng-model:

<input type="text" ng-model="myText">

控制器:

$scope.$watch('myText', function() {
   // put logic to strip out all non-character characters here
   if ($scope.myText  ... regex to look for ... ) {
      // strip out the non-characters
   }
})

最佳方式,在指令中使用$ parser。 我不打算重复@ pkozlowski.opensource提供的已经很好的答案,所以这里是链接:https://stackoverflow.com/a/14425022/215945

不要尝试使用ng-change - 它会导致问题。见AngularJS - reset of $scope.value doesn't change value in template (random behavior)

<强>更新 ng-pattern也可用于定义将限制字段中允许的内容的正则表达式。另请参阅"cookbook" page about forms

相关问题