Forms are a crucial part of any web application, allowing users to input and submit data. AngularJS provides powerful features to create, validate, and manage forms efficiently. Its two-way data binding, directives, and built-in validators simplify the development of dynamic and interactive forms.
In this guide, we’ll explore how to create and manage forms in AngularJS, focusing on practical examples and best practices. Visit The Coding College for more insightful tutorials on AngularJS and web development.
Key Features of AngularJS Forms
- Two-Way Data Binding: Automatically synchronizes form inputs with the model.
- Validation: Provides built-in validators and the ability to create custom ones.
- Directives: Simplifies form creation (
ng-model
,ng-submit
, etc.). - Form States: Tracks the validity and status of forms and their controls.
Creating Forms with AngularJS
Basic Form Example
<div ng-app="myApp" ng-controller="formCtrl">
<form ng-submit="submitForm()">
<label>Name:</label>
<input type="text" ng-model="user.name" required>
<br>
<label>Email:</label>
<input type="email" ng-model="user.email" required>
<br>
<button type="submit">Submit</button>
</form>
<p>{{ user }}</p>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.user = {};
$scope.submitForm = function() {
alert('Form submitted! Name: ' + $scope.user.name + ', Email: ' + $scope.user.email);
};
});
</script>
Output: The form captures user details and displays them upon submission.
AngularJS Form Validation
AngularJS provides built-in validation for common input types, such as required
, email
, number
, and more.
Example: Form with Validation
<div ng-app="myApp" ng-controller="formCtrl">
<form name="userForm" ng-submit="submitForm()" novalidate>
<label>Name:</label>
<input type="text" name="name" ng-model="user.name" required>
<span ng-show="userForm.name.$touched && userForm.name.$invalid">Name is required.</span>
<br>
<label>Email:</label>
<input type="email" name="email" ng-model="user.email" required>
<span ng-show="userForm.email.$touched && userForm.email.$invalid">Enter a valid email.</span>
<br>
<button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.user = {};
$scope.submitForm = function() {
alert('Form submitted successfully!');
};
});
</script>
Features:
- Displays error messages for invalid inputs.
- Disables the submit button until the form is valid.
Tracking Form States
AngularJS tracks various form and input states:
- $dirty: True if the input value has been changed.
- $pristine: True if the input value is untouched.
- $touched: True if the input field has been focused and then blurred.
- $valid and $invalid: Indicate the validity of the input or form.
Example: Displaying Form States
<div ng-app="myApp" ng-controller="formCtrl">
<form name="userForm" novalidate>
<label>Username:</label>
<input type="text" name="username" ng-model="user.username" required>
<p>Dirty: {{ userForm.username.$dirty }}</p>
<p>Pristine: {{ userForm.username.$pristine }}</p>
<p>Touched: {{ userForm.username.$touched }}</p>
<p>Valid: {{ userForm.username.$valid }}</p>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.user = {};
});
</script>
Output: Displays the current state of the input field.
Custom Validation
You can create custom validation logic using AngularJS directives.
Example: Custom Validator for Password
<div ng-app="myApp" ng-controller="formCtrl">
<form name="passwordForm" novalidate>
<label>Password:</label>
<input type="password" name="password" ng-model="user.password" validate-password>
<span ng-show="passwordForm.password.$error.invalidPassword">Password must be at least 8 characters long.</span>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.directive('validatePassword', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
ctrl.$validators.invalidPassword = function(modelValue) {
return modelValue && modelValue.length >= 8;
};
}
};
});
</script>
Output: Displays a validation error if the password is less than 8 characters.
Resetting Forms
To reset a form to its pristine state, use the form.$setPristine()
and form.$setUntouched()
methods.
Example: Reset Button
<div ng-app="myApp" ng-controller="formCtrl">
<form name="userForm" novalidate>
<label>Name:</label>
<input type="text" name="name" ng-model="user.name" required>
<br>
<label>Email:</label>
<input type="email" name="email" ng-model="user.email" required>
<br>
<button type="button" ng-click="resetForm()">Reset</button>
</form>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('formCtrl', function($scope) {
$scope.user = {};
$scope.resetForm = function() {
$scope.user = {};
$scope.userForm.$setPristine();
$scope.userForm.$setUntouched();
};
});
</script>
Output: Clears the form inputs and resets the validation states.
Best Practices for AngularJS Forms
- Use Built-In Validation: Leverage AngularJS’s built-in validators for common use cases.
- Custom Validation: Implement custom validators for unique requirements.
- Error Messages: Display user-friendly error messages for invalid inputs.
- Avoid Inline JavaScript: Keep validation logic in directives or the controller.
- Accessibility: Ensure forms are accessible by using proper labels and ARIA attributes.
Conclusion
AngularJS offers a comprehensive set of tools for creating and managing forms, making it easy to validate user input and handle form states. By following best practices and leveraging AngularJS features, you can build user-friendly and efficient forms.