AngularJS-使用ui-validate显示自定义错误ngMessage

时间:2018-06-22 10:46:04

标签: angularjs validation angular-ui ng-messages ui-validate

我是AngularJS的新手,我想实现的目标是使用ui-validate创建自定义ngMessage。在此代码中,有2个文本框供用户输入数字,我创建了一个条件,其中第二个数字必须小于第一个数字。在ui验证中调用了此条件。

请参见以下代码:

var app = angular.module('ngMessagesExample', ['ngMessages', 'ui.validate']);

app.controller('ctl', function ($scope) {
  $scope.data = {};
  $scope.validateInput = function($value) {
    
    if ($value > $scope.data.field1) {
        /* show the custom ng-message
        "validationError" error */
    }
    else {
        /* don't show error in the ng-message */
    }
  };
  
  $scope.submitForm = function(isValid) {
    alert("all fields are valid.");
  };
  
});
<!doctype html>
<html>
<head>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular.min.js"></script>
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.0/angular-messages.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-validate/1.2.3/validate.min.js"></script>
  <script src="script.js"></script>
</head>
<body ng-app="ngMessagesExample" ng-controller="ctl">
  
  <form name="myForm" novalidate ng-submit="submitForm(myForm.$valid)">
    <label>
      1st Number:  
      <input type="number"
             ng-model="data.field1"
             name="field1" required />
    </label>
     <div ng-messages="myForm.field1.$error" ng-show="myForm.field1.$touched && myForm.field1.$invalid" style="color:red">
        <div ng-message="required">this is required</div>
    </div>
    <br>
    <label>
      2nd Number:  
      <input type="number"
             ng-model="data.field2"
             name="field2" required ui-validate="validateInput($value)" />
    </label>
    <div ng-messages="myForm.field2.$error" ng-show="myForm.field2.$touched && myForm.field2.$invalid" style="color:red">
        <div ng-message="validationError">2nd Number must be less than 1st Number</div>
        <div ng-message="required">this is required</div>
    </div>
  
  <br/><br/>
  <button style="float:left" type="submit" ng-disabled="myForm.$invalid">Submit</button>
</form>

</body>
</html>

有人可以帮我吗?我为此创建了一个Plunker。预先感谢!

0 个答案:

没有答案