WICS2 SRC
WICS2 SRC

Reputation: 216

Setting up multiple forms / validations on same page

What's up all, total AngularJS noob here and looking for some answers.

I have a page set up like so:

    <form name="mainForm" class="content" ng-app="pathForm" ng-controller="FormControl" novalidate>

    <div class="full-page open" id="form1">
    <!-- Form 1 content here -->
    </div>  

    <div class="full-page" id="form2">
    <!-- Form 2 content here -->
    </div>

    <div class="full-page" id="form3">
    <!-- Form 3 content here -->
    </div>

    <div class="full-page" id="form4">
    <!-- Form 4 content here -->
    </div>

</form>

Where each of these forms have their own set of inputs that need validation. I've been able to get the validation working across all four forms, because I set up an encompassing form ng-app that cover all 4 forms. On submit, a script removes the 'open' class from the open form, cycles to the enxt form and adds the open class on that form.

How can I set it so that each one of these forms can be individually validated?

Thanks in advance.

Upvotes: 11

Views: 14142

Answers (1)

Sharikov Vladislav
Sharikov Vladislav

Reputation: 7269

You need ngForm directive and FormController.

Each ng-form directive with name in this directive adds property to the $scope. You can access this property (it is object, instance of FormController) in function called by submit button click.

There are some properties and methods in this object. You need property $valid (or $invalid) to get validation status of your forms.

HTML:

<ng-form name="form1"></ng-form>
<ng-form name="form2"></ng-form>
<button ng-click="submit();">Submit</button>

JS:

$scope.submit = function () {
    if ($scope.form1.$valid && $scope.form2.$valid) {}
}

Custom validators If built-in validators are not enought you can add your own custom validators.

See docs and this post on so.com.

Upvotes: 10

Related Questions