Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 399
WICS2 SRC Avatar asked Nov 16 '15 22:11

WICS2 SRC


People also ask

What is form validation server-side?

When you enter data, the browser and/or the web server will check to see that the data is in the correct format and within the constraints set by the application. Validation done in the browser is called client-side validation, while validation done on the server is called server-side validation.


1 Answers

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.

like image 119
Sharikov Vladislav Avatar answered Sep 21 '22 04:09

Sharikov Vladislav