角度相关的场验证

时间:2016-02-16 11:16:13

标签: javascript html angularjs validation select

我遇到了问题。我正在尝试为我的表单创建验证指令。我的验证过程有点复杂。我有4个选择(下拉菜单)。第一个团队(用户和代理人)的2个下拉列表和第二个团队的下拉列表。

我的验证指令需要执行以下操作:

  1. 选择用户第一队但不是副队第一队(需要副一队)

  2. 选择了第一副队,但不是用户第一队(需要用户第一队)

  3. 选择用户第二队但不是副二队(需要副二队)
  4. 选择了第二个副团队但未选择用户第二个团队(需要用户第二个团队)
  5. 没有选择第一或第二队的用户或代理人(至少需要一名用户或代理人)
  6. 我的HTML看起来像这样:

            <div class="row" ng-form="reportForm" ng-model="report" require-users>                
                <!-- User First Team -->
                <div class="col-sm-3 col-xs-6">
                    <div class="form-group">
                        <label>User First Team</label>
                        <!-- Dropdown User First Team -->
                        <select ng-form="reportForm.userFirst" 
                                ng-model="report.userFirst" 
                                ng-options="user.Name for user in users track by user.Id" 
                                class="form-control">
                            <option></option>
                        </select>
    
                        <!-- Error Messages-->
                        <div ng-messages="reportForm.$error" style="color:maroon; margin-top: 4px;" role="alert">
                            <!-- Message required -->
                            <div ng-message="requireUserFirst">
                                <small>A User for the first team is required.</small>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Deputy First Team -->
                <div class="col-sm-3 col-xs-6">
                    <div class="form-group">
                        <label>Deputy First Team</label>
                        <!-- Dropdown Deputy First Team -->
                        <select ng-form="reportForm.deputyFirst" 
                                ng-model="report.deputyFirst" 
                                ng-options="user.Name for user in users track by user.Id" 
                                class="form-control">
                            <option></option>
                        </select>
    
                         <!-- Error messages -->
                        <div ng-messages="reportForm.$error" style="color:maroon; margin-top: 4px;" role="alert">
                            <!-- Message required -->
                            <div ng-message="requireDeputyFirst">
                                <small>A Deputy for the first team is required.</small>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- User Second Team -->
                <div class="col-sm-3 col-xs-6">
                    <div class="form-group">
                        <label>User Second Team</label>
                        <!-- Dropdown User Second Team -->
                        <select ng-form="reportForm.userSecond" 
                                ng-model="report.userSecond" 
                                ng-options="user.Name for user in users track by user.Id" 
                                class="form-control">
                            <option></option>
                        </select>
    
                         <!-- Error messages -->
                        <div ng-messages="reportForm.$error" style="color:maroon; margin-top: 4px;" role="alert">
                           <!-- Message required -->
                            <div ng-message="requireUserSecond">
                                <small>A User for the second team is required.</small>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Deputy Second Team -->
                <div class="col-sm-3 col-xs-6">
                    <div class="form-group">
                        <label>Deputy Second Team</label>
                        <!-- Dropdown Deputy Second Team -->
                        <select ng-form="reportForm.deputySecond" 
                                ng-model="report.deputySecond" 
                                ng-options="user.Name for user in users track by user.Id" 
                                class="form-control">
                            <option></option>
                        </select>
    
                         <!-- Error messages -->
                        <div ng-messages="reportForm.$error" style="color:maroon; margin-top: 4px;" role="alert">
                            <!-- Message required -->
                            <div ng-message="requireDeputySecond">
                                <small>A Deputy for the second team is required.</small>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- Error messages -->
                <div ng-messages="reportForm.$error" style="color:maroon; margin-top: 4px;" role="alert" class="col-xs-12">
                    <!-- Message missing user and deputy -->
                    <div ng-message="requireAll">
                        <small><strong>At least one user and deputy is needed.</strong></small>
                    </div>
                </div>
      </div>
    

    我的指示在这里:

    app.directive('requireUsers', function () {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function (scope, elem, attr, ngModel) {
                scope.$watch(function () {
                    return ngModel.$modelValue;
                }, function (model, oldModel) {
                    if (model != oldModel) {
    
                        if (model.userFirst == null && model.deputyFirst == null && model.userSecond == null && model.deputySecond == null) {
                            ngModel.$setValidity('requireAll', false);
                        } else {
                            ngModel.$setValidity('requireAll', true);
                        }
    
                        if ((model.userFirst == undefined || model.userFirst == null) && model.deputyFirst != null) {
                            ngModel.$setValidity('requireUserFirst', false);
                        } else {
                            ngModel.$setValidity('requireUserFirst', true);
                        }
    
                        if ((model.deputyFirst == undefined || model.deputyFirst == null) && model.userFirst != null) {
                            ngModel.$setValidity('requireDeputyFirst', false);
                        } else {
                            ngModel.$setValidity('requireDeputyFirst', true);
                        }
    
                        if ((model.userSecond == undefined || model.userSecond == null) && model.deputySecond != null) {
                            ngModel.$setValidity('requireUserSecond', true);
                        } else {
                            ngModel.$setValidity('requireUserSecond', true);
                        }
    
                        if ((model.deputySecond == undefined || model.deputySecond == null) && model.userSecond != null) {
                            ngModel.$setValidity('requireDeputySecond', false);
                        } else {
                            ngModel.$setValidity('requireDeputySecond', true);
                        }
                    }
                });
            }
        };
    });
    

    问题是观察者只有在指令初始化时才能工作。因此,当我更改值时,验证过程将无法启动。

    UPDATE ReportController:

    angular.module('ReportTool')
        .controller('ReportController', ['$scope', 'Report', 'User', function ($scope, Report, User) {
            var _this = this;
    
            // Load all Teammembers (API Call in Service)
            User.query().then(function (success) {
                _this.users= success.data;
            }, function (error) {
                console.log('Users could not be loaded.');
            });            
    
            // Save report
            this.save = function () {
                if (_this.report != null) {
                    // create report
                    Report.post(_this.report).then(function (success) {
                        console.log('Report created.');
                    }, function (error) {
                        console.log('Report could not be created.');
                } else {
                    console.log('Report is null.');
                }
            };
        }]);
    

2 个答案:

答案 0 :(得分:0)

在这种情况下,您需要为每个检查编写指令,例如requireUsers

我建议使用指令use-form-error。 可以轻松创建自定义检查。

jsfiddle上的实例。

&#13;
&#13;
angular.module('ExampleApp', ['use', 'ngMessages'])
  .controller('ExampleController', function($scope) {

  });
&#13;
.errors {
  color: maroon
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://cdn.rawgit.com/Stepan-Kasyanenko/use-form-error/master/src/use-form-error.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-messages.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController">

    <form name="myForm">
      <label>User first:</label>
      <input type="text" ng-model="userFirst" name="userFirst" use-form-error="requireUserFirst" use-error-expression="!userFirst && deputyFirst" />
      <br>
      <label>Deputy first:</label>
      <input type="text" ng-model="deputyFirst" name="deputyFirst" use-form-error="requireDeputyFirst" use-error-expression="userFirst && !deputyFirst"/>
      <br>
      <hr>

      <label>User second:</label>
      <input type="text" ng-model="userSecond" name="userSecond" />
      <br>
      <label>Deputy second:</label>
      <input type="text" ng-model="deputySecond" name="deputySecond" />
      <br>

      <div use-form-error="requireAll" use-error-expression="!userFirst && !deputyFirst && !userSecond && !deputySecond" use-error-input="myForm"> </div>
      <div ng-messages="myForm.$error" class="errors">
        <div ng-message="requireAll">At least one user and deputy is needed.</div>
      </div>
      <div ng-messages="myForm.userFirst.$error" class="errors">
        <div ng-message="requireUserFirst">A User for the first team is required.</div>
      </div>
      <div ng-messages="myForm.deputyFirst.$error" class="errors">
        <div ng-message="requireDeputyFirst">A Deputy for the first team is required.</div>
      </div>
    </form>

  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以将变量简单地传递到directive。然后检查一下。

jsfiddle上的现场示例。

angular.module('ExampleApp', ['ngMessages'])
  .controller('ExampleController', function($scope) {

  })
  .directive('requireUsers', function() {
    return {
      restrict: 'A',
      require: 'form',
      scope: {
        userFirst: "=",
        deputyFirst: "=",
        userSecond: "=",
        deputySecond: "=",
      },
      link: function(scope, elem, attr, ngModel) {
        function changeValue(model, oldModel) {
          if (!scope.userFirst && !scope.deputyFirst && !scope.userSecond && !scope.deputySecond) {
            ngModel.$setValidity('requireAll', false);
          } else {
            ngModel.$setValidity('requireAll', true);
          }

          if (!scope.userFirst && scope.deputyFirst) {
            ngModel.$setValidity('requireUserFirst', false);
          } else {
            ngModel.$setValidity('requireUserFirst', true);
          }

          if (!scope.deputyFirst && scope.userFirst) {
            ngModel.$setValidity('requireDeputyFirst', false);
          } else {
            ngModel.$setValidity('requireDeputyFirst', true);
          }

          if (!scope.userSecond && scope.deputySecond) {
            ngModel.$setValidity('requireUserSecond', false);
          } else {
            ngModel.$setValidity('requireUserSecond', true);
          }

          if (!scope.deputySecond && scope.userSecond) {
            ngModel.$setValidity('requireDeputySecond', false);
          } else {
            ngModel.$setValidity('requireDeputySecond', true);
          }
        }
        scope.$watch('userFirst', changeValue);
        scope.$watch('deputyFirst', changeValue);
        scope.$watch('userSecond', changeValue);
        scope.$watch('deputySecond', changeValue);
      }
    };
  });;
.errors {
  color: maroon
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular-messages.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="ExampleController">

    <form name="myForm" require-users user-first="userFirst" deputy-first="deputyFirst" user-second="userSecond" deputy-second="deputySecond">
      <label>User first:</label>
      <input type="text" ng-model="userFirst" name="userFirst" />
      <br>
      <label>Deputy first:</label>
      <input type="text" ng-model="deputyFirst" name="deputyFirst" />
      <br>
      <hr>

      <label>User second:</label>
      <input type="text" ng-model="userSecond" name="userSecond" />
      <br>
      <label>Deputy second:</label>
      <input type="text" ng-model="deputySecond" name="deputySecond" />
      <br>


      <div ng-messages="myForm.$error" class="errors">
        <div ng-message="requireAll">At least one user and deputy is needed.</div>
        <div ng-message="requireUserFirst">A User for the first team is required.</div>
        <div ng-message="requireDeputyFirst">A Deputy for the first team is required.</div>
        <div ng-message="requireUserSecond">A User for the second team is required.</div>
        <div ng-message="requireDeputySecond">A Deputy for the second team is required.</div>
      </div>
    </form>

  </div>
</div>