【问题标题】:Allow only characters in textbox using AngularJs使用 AngularJs 只允许文本框中的字符
【发布时间】:2013-02-02 18:54:16
【问题描述】:

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

【问题讨论】:

标签: javascript angularjs angularjs-directive


【解决方案1】:

骇客?方式,$watch 控制器中的 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

【讨论】:

  • 看来你不明白我的问题。我希望该用户不能在文本框中输入除字符以外的任何值。所以我认为在这里我们必须使用 onkeypress 功能。你说什么??
  • 我相信我提供的两种解决方案应该可行。我刚刚用有关 ng-pattern 的信息更新了我的答案。如果您无法使用这三种解决方案之一使其工作,请发布您尝试过的fiddleplnkr
  • 我已经为此目的使用了 ng-pattern 并且它很好地用于验证目的,但实际上现在我希望该用户甚至不能在文本框中输入除字符之外的任何内容。你能帮我解决这个问题吗?
  • 请参阅stackoverflow.com/a/15556249/215945,其中编写了一条指令以防止输入非数字字符。只需将指令中的正则表达式更改为只允许字符。
猜你喜欢
  • 2013-04-12
  • 1970-01-01
  • 2012-09-18
  • 1970-01-01
  • 2010-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多