简体   繁体   English

AngularJS 中的动态表单验证 - 有更好的解决方案/方法吗?

[英]Dynamic form validation in AngularJS - Is there a better solution/approach?

I am able to create a basic dynamic form validation for an AngularJS app.我能够为 AngularJS 应用程序创建一个基本的动态表单验证。 It's one of those combo box + input field forms example so that when I change the combo box, a new set of validation rule gets applied to the input field.它是组合框 + 输入字段表单示例之一,因此当我更改组合框时,一组新的验证规则将应用于输入字段。 To keep things simple for this example, I just used a variable maxlength that changes when I select a different criteria in the combo box.为了让这个例子简单,我只使用了一个变量 maxlength,当我在组合框中选择不同的条件时,该变量会发生变化。 In my real app, I'm also using regex pattern but same concept, a different pattern gets applied on combo box change.在我的真实应用程序中,我也使用正则表达式模式,但相同的概念,不同的模式应用于组合框更改。

JSFiddle Example JSFiddle 示例

var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', ['$scope', function($scope) {
      $scope.maxlength = 1;

      $scope.change = function() {
        if($scope.type==='LastName') {
          $scope.maxlength = 10;
        }
        else if($scope.type==='UserName') {
          $scope.maxlength = 6;
        }
      }
    }]);

My question is: is there a better solution than this?我的问题是:还有比这更好的解决方案吗? I'm still new to Angular and currently learning how to do things the proper way.我还是 Angular 的新手,目前正在学习如何以正确的方式做事。 Currently, this serves my purpose, but I'm hoping any AngularJS experts out there can suggest a better solution than what I have.目前,这符合我的目的,但我希望那里的任何 AngularJS 专家都可以提出比我所拥有的更好的解决方案。 Thanks.谢谢。

You could have an array of rules, and bind the values of the selected rules to the validation directives like this.您可以拥有一组规则,并将所选规则的值绑定到这样的验证指令。

 var myApp = angular.module('myApp', []); myApp.controller('MyCtrl', ['$scope', function($scope) { $scope.rules = [{ name: 'UserName', maxLength: 6 }, { name: 'FirstName', maxLength: 8 }, { name: 'LastName', maxLength: 10 }]; $scope.selectedRule = $scope.rules[0]; $scope.search = ''; } ]);
 <div ng-app="myApp" ng-controller="MyCtrl"> <form name="myForm" novalidate> <select ng-options="rule.name for rule in rules" ng-model="selectedRule"> <option ng-repeat="rule in rules" value="{{rule}}">{{rule.name}}</option> </select> <input name="searchbox" ng-model="search" ng-maxlength="selectedRule.maxLength" /> </form> <tt>input valid? = {{myForm.searchbox.$valid}}</tt> <br> <tt>maxlength = {{selectedRule.maxLength}}</tt> <br/> <tt>type = {{selectedRule.name}}</tt> <br/> </div> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM