Typically to validate a form in Angular, I would use something like this on the ng-submit
directive:
<form name="formName" ng-submit="formName.$valid && submitForm()"></form>
This works great when the form has a name that I set myself while building the form. However, in my current situation, I am trying to create multiple forms based on a list of objects. In this case, each form has a name that is determined on the fly.
When the user submits one of these forms, how can I validate it before running the submitForm()
function for that form?
Here's a jsfiddle of the simplified problem: http://jsfiddle.net/flyingL123/ub6wLewc/1/
My question is, how can I access the name of the form in order to validate it? Here is the code from the fiddle:
var app = angular.module('app', []);
app.controller("AppController", ['$scope', function($scope) {
$scope.forms = [{
id: 1,
value: "val1"
}, {
id: 2,
value: "val2"
}, {
id: 3,
value: "val3"
}];
$scope.submitForm = function() {
alert('submitted');
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>
<div id="app" ng-app="app" ng-controller="AppController">
<div class="formWrapper" ng-repeat="form in forms">
<form name="{{ 'form' + form.id }}" ng-submit="submitForm()" novalidate>
<input ng-model="form.value" required />
<button type="submit">Submit</button>
</form>
</div>
</div>
Dynamically Add Validators We need to listen to optionB value changes and based on that we add or remove the validators we require. We also call the control's updateValueAndValidity() method, as we need to recalculate the value and validation status of the control.
We can add Validators dynamically using the SetValidators or SetAsyncValidators. This method is available to FormControl, FormGroup & FormArray. There are many use cases where it is required to add/remove validators dynamically to a FormControl or FormGroup.
Dynamic Validation validates Snap properties as you enter them. SnapLogic starts validating a property as you edit it; a preview of the result of this validation is displayed and updated as you continue editing.
You can always use this
to access the scope in your templates.
{{this.foo === foo}} <!-- This will always show "true" -->
Therefore, you can simply use this[myDynamicFormName]
to access the form:
<form name="{{'form' + form.id}}" ng-submit="this['form' + form.id].$valid && submitForm()"></form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With