How do I check form validity with angularjs?
AngularjsAngularjs Problem Overview
I'm very new to angularjs. Say my app has a form. Using the inspector, I noticed that if angularjs thinks that the form is invalid, it adds an ng-invalid class to the form. Lovely.
So it seems that in order to check if the form is valid I need to pollute my code with Jquery selector?! What is the angularjs way to indicate form validity without using a form controller?
Angularjs Solutions
Solution 1 - Angularjs
When you put <form>
tag inside you ngApp, AngularJS automatically adds form controller (actually there is a directive, called form
that add nessesary behaviour). The value of the name attribute will be bound in your scope; so something like <form name="yourformname">...</form>
will satisfy:
> A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute.
So to check form validity, you can check value of $scope.yourformname.$valid
property of scope.
More information you can get at Developer's Guide section about forms.
Solution 2 - Angularjs
Example
<div ng-controller="ExampleController">
<form name="myform">
Name: <input type="text" ng-model="user.name" /><br>
Email: <input type="email" ng-model="user.email" /><br>
</form>
</div>
<script>
angular.module('formExample', [])
.controller('ExampleController', ['$scope', function($scope) {
//if form is not valid then return the form.
if(!$scope.myform.$valid) {
return;
}
}]);
</script>
Solution 3 - Angularjs
You can also use myform.$invalid
E.g.
if($scope.myform.$invalid){return;}
Solution 4 - Angularjs
form
- directive in module ng Directive that instantiates FormController.
If the name attribute is specified, the form controller is published onto the current scope under this name.
Alias: ngForm
In Angular, forms can be nested. This means that the outer form is valid when all of the child forms are valid as well. However, browsers do not allow nesting of