Reputation: 193
I am able to create a basic dynamic form validation for an AngularJS app. 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. In my real app, I'm also using regex pattern but same concept, a different pattern gets applied on combo box change.
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. Currently, this serves my purpose, but I'm hoping any AngularJS experts out there can suggest a better solution than what I have. Thanks.
Upvotes: 1
Views: 242
Reputation: 7164
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>
Upvotes: 1