In AngularJS, how to force the re-validation of a field in a form when another value in the same form is changed? -
i have form few fields, select , input field coupled: validation on input depends on value user chooses in select field.
i'll try clarify example. let's select contains names of planets:
<select id="planet" class="form-control" name="planet" ng-model="planet" ng-options="c.val c.label c in planets"></select>
in input apply custom validation via custom directive named "input-validation":
<input id="city" input-validation iv-allow-if="planet==='earth'" class="form-control" name="city" ng-model="city" required>
where directive:
.directive('inputvalidation', [function() { return { require: 'ngmodel', restrict: 'a', scope: { ivallowif: '=' }, link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.unshift(function(viewvalue) { //input allowed if attribute not present or expression evaluates true var inputallowed = attrs.ivallowif === undefined || scope.$parent.$eval(attrs.ivallowif); if (inputallowed) { ctrl.$setvalidity('iv', true); return viewvalue; } else { ctrl.$setvalidity('iv', false); return undefined; } }); } }; }])
the full example can examined in plnkr: http://plnkr.co/edit/t2xmpy1ehvfa5knedfrf?p=preview
whenever select modified, need input verified again. not happening in code. doing wrong?
i have done same thing validation of start-date on change of end-date. in directive of start-date add watch change of end-date , call ngmodel.$validate()
in case end-date new value defined.
scope.$watch(function () { return $parse(attrs.enddate)(scope); }, function () { ngmodel.$validate(); });
the important part take call ngmodel.$validate()
inside directive.
note should use $validators custom validations above work. read here, $parsers old way - angularjs 1.3 use $validators
Comments
Post a Comment