Antelle Antelle - 6 months ago 143
AngularJS Question

Skip nested forms validation with AngularJS

How can I skip validation of nested forms with AngularJS? I have to make an outer form valid even when its child form is invalid.

In the example below outer form should be valid (

fOuter.$valid
must be true). By default, it is not. Is there an option?

Code (jsFiddle):

<div ng-app ng-controller="Ctrl">
<ng-form name="fOuter">
<h3>Outer form (valid={{fOuter.$valid}})</h3>
<input type="text" name="txtOuter" ng-model="outer" placeholder="(required)" required />
<ng-form name="fInner">
<h3>Inner form (valid={{fInner.$valid}})</h3>
<input type="text" name="txtInner" ng-model="inner" placeholder="(required)" required />
</ng-form>
</ng-form>
</div>

Answer

In Angular forms can be nested. This means that the outer form is valid when all of the child forms are valid as well.

So there is no way to make outer form to be valid automatically (through $valid key) when one of inner invalid.

Try to use error.required

   <h3>Outer form (valid={{!fOuter.txtOuter.$error.required}})</h3>

Demo Fiddle

From Angular ngForm docs:

The other way should be to use controller, like:

<h3>Outer form (valid={{isOuterFormValid}})</h3>

controller

$scope.isOuterFormValid = true;

// here, add listener on each input and change flag `isOuterFormValid`
... 
Comments