Forms & Validation
Form with required, minlength, email validation, and disabled submit.
Code
<div ng-controller="FormController as vm">
<form name="userForm" ng-submit="vm.submit()" novalidate>
<label>Name:</label>
<input type="text" name="name" ng-model="vm.user.name"
required minlength="2">
<span ng-show="userForm.name.$touched && userForm.name.$error.required">
Required
</span>
<span ng-show="userForm.name.$error.minlength">Too short</span>
<label>Email:</label>
<input type="email" name="email" ng-model="vm.user.email" required>
<span ng-show="userForm.email.$touched && userForm.email.$error.email">
Invalid email
</span>
<button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>
</div>
<script>
angular.module('formsApp', [])
.controller('FormController', function() {
const vm = this;
vm.user = {};
vm.submit = function() {
if (this.userForm.$valid) {
console.log('Submitted:', vm.user);
}
};
});
</script>Explanation
AngularJS augments forms with state flags ($valid, $invalid, $touched, $dirty) and per-field $error objects keyed by validator. novalidate disables the browser's native validation so AngularJS handles it. ng-disabled on the submit button prevents invalid submissions; access the form via its name attribute on the controller's this.
More AngularJS Snippets
Module & Controller
Define a module and a controller with scope methods.
Scope Inheritance
Prototypal scope inheritance between parent and child controllers.
Custom Directives
Attribute directive and element directive with isolated scope.
Services & Factories
Factory and service singletons for shared state and logic.
Routing (ngRoute)
Configure routes with templates, controllers, and resolve guards.
Custom Filters
Chainable filters for formatting values in templates.