angularJs使用动态错误消息形成valiation

时间:2016-02-16 11:52:34

标签: javascript jquery html angularjs angularjs-directive

我想验证一个表单,其中每个输入可能根据输入有许多错误消息。我想从javaScript编写这些错误消息。

HTML

<input name="username" ng-model="user.username" type="text" placeholder="Username" required>
<div class="field-message" ng-messages="frm.username.$error" ng-if='frm.username.$dirty' ng-cloak>
     <div ng-message="required">Username is required</div>
</div>

JS

angular.module('DemoApp', ['ngMessages']);    
angular.bootstrap(document.getElementById('demoApp'), ['DemoApp']);

在上面的代码中,ng-message指令有错误消息,如果输入无效,将显示该消息。如果有很多案例需要验证,并且每个案例都有不同的错误消息,那么多个ng-message必须在html中添加特定的输入控件。

我想只在html中输入标签,而错误信息则来自javascript。

任何一位指南都可以实现这一目标吗? 感谢。

1 个答案:

答案 0 :(得分:2)

请参阅此问题:How to add custom validation to an AngularJS form?

总结:

您可以使用ui-validate

您可以像这样创建自定义验证(从原始问题的答案中复制):

app.directive('blacklist', function (){ 
   return {
      require: 'ngModel',
      link: function(scope, elem, attr, ngModel) {
          var blacklist = attr.blacklist.split(',');

          //For DOM -> model validation
          ngModel.$parsers.unshift(function(value) {
             var valid = blacklist.indexOf(value) === -1;
             ngModel.$setValidity('blacklist', valid);
             return valid ? value : undefined;
          });

          //For model -> DOM validation
          ngModel.$formatters.unshift(function(value) {
             ngModel.$setValidity('blacklist', blacklist.indexOf(value) === -1);
             return value;
          });
      }
   };
});

以下是一些示例用法:

<form name="myForm" ng-submit="doSomething()">
   <input type="text" name="fruitName" ng-model="data.fruitName" blacklist="coconuts,bananas,pears" required/>
   <span ng-show="myForm.fruitName.$error.blacklist">
      The phrase "{{data.fruitName}}" is blacklisted</span>
   <span ng-show="myForm.fruitName.$error.required">required</span>
   <button type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>

编辑:根据OP的要求,仅打印相关错误:

Plunkr:http://plnkr.co/edit/KN0Oukb8uACvZjtGPUg4?p=preview

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {
  $scope.doSomething = function() {
    alert('Submitted!');
  }

  $scope.getErrors = function() {
    if ($scope.myForm.fruitName.$error.required) {
      return 'This field is required';
    } else if ($scope.myForm.fruitName.$error.blacklist) {
      return 'The phrase ' + $scope.data.fruitName + ' is blacklisted';
    }
  }
});

app.directive('blacklist', function() {
  return {
    require: 'ngModel',
    link: function(scope, elem, attr, ngModel) {
      var blacklist = attr.blacklist.split(',');
      ngModel.$parsers.unshift(function(value) {
        ngModel.$setValidity('blacklist', blacklist.indexOf(value) === -1);
        return value;
      });
    }
  };
});
.invalid {
  color: red;
}
.ng-invalid {
  border-color: red;
}
<!DOCTYPE html>
<html ng-app="angularjs-starter">
    <head lang="en">
    <meta charset="utf-8">
    <title>Custom Plunker</title>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
  </head>
  
  <body ng-controller="MainCtrl">
    <form name="myForm" ng-submit="doSomething()">
       <div>Please <u>don't</u> type the words: coconuts, bananas or pears.</div>
       <input type="text" name="fruitName" ng-model="data.fruitName" blacklist="coconuts,bananas,pears" required/>
       <span class="invalid" ng-show="myForm.fruitName.$error">{{getErrors()}}</span>
       <br/>
       <button type="submit" ng-disabled="myForm.$invalid">Submit</button>
       <button type="button" ng-click="getErrors()">Get errors</button>
    </form>
  </body>
</html>