显示无效输入的错误消息

时间:2015-06-12 07:54:36

标签: angularjs

我想在用户在文本字段中输入无效输入时显示错误消息。

现在我正在使用:

Pin:<input type="text" class="form-control input-sm" ng-pattern="numOnlyRegex" name="pin" ng-model="pin" required placeholder="Pin"/>
<span style="color:red" ng-show="myForm.pin.$invalid">Only number are allowed</span>
<input type="Submit" class="form-control btn btn-success" ng-disabled="myForm.$invalid" value="Submit" />

控制器:

<script>
            angular.module('myApp', []).controller("numOnlyRegex", function ($scope)
            {
                $scope.numOnlyRegex = /^\d+$/;
            });
        </script>

但我正在尝试的上述方式在输入文本字段下方显示静态消息。我想要的是当用户输入字母而不是数字时,它应该显示错误消息,例如“只允许数字”,否则它不应显示任何错误消息。

ng-show方法在输入为空时显示静态消息,但我想仅在出现错误时显示错误(更实际的方式)

3 个答案:

答案 0 :(得分:5)

您可以在表单上使用$ error.pattern来显示特定的错误消息

<span style="color:red" ng-show="myForm.pin.$error.pattern">Invalid Input</span>

以下是$ error

的其他一些示例
myForm.useremail.$error.email ==true 
   // When useremail field does not contain a real email.
myForm.username.$error.require ==true
   // Only if the username field is left blank.

这里是plunkr

答案 1 :(得分:2)

Angular允许您定位特定错误。在这种情况下,您可以使用无效模式错误:

<span style="color:red" ng-show="myForm.pin.$error.pattern">Only number are allowed</span>

这样它只会在模式验证时显示错误。

请参阅this JSFIDDLE

答案 2 :(得分:0)

&#13;
&#13;
angular.module('myApp',[]).controller('myFormController',['$scope',function($scope){
  $scope.myInputVal='';
}])
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<html>
  <body ng-app="myApp">
  <div ng-controller="myFormController">
     <form name="myForm" >
     <input type="text" ng-model="myInputVal" ng-pattern="/^[0-9]*$/" name="myInputVal"/>
     <span ng-show="myForm.myInputVal.$error.pattern">Only Numbers are allowed</span>
     <span ng-show="!myForm.myInputVal.$error.pattern">{{myInputVal}}</span>
     <button type="submit" ng-disabled="myForm.$invalid">Submit</button>
     </form>
     </div>
  </body>
  
&#13;
&#13;
&#13;