AngularJS — Validation
Built-in Validators
| Attribute | Description |
|---|---|
| required | Field required |
| ng-minlength | Minimum length |
| ng-maxlength | Maximum length |
| ng-pattern | Regex pattern |
| Email format | |
| number | Number format |
Validation Example
<form name="userForm" ng-submit="submitForm()">
<input name="name" ng-model="user.name" required ng-minlength="3">
<span ng-show="userForm.name.$error.required">Name is required</span>
<span ng-show="userForm.name.$error.minlength">Minimum 3 characters</span>
<input name="email" ng-model="user.email" required email>
<span ng-show="userForm.email.$error.required">Email is required</span>
<span ng-show="userForm.email.$error.email">Invalid email</span>
<button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>
Validation States
$scope.submitForm = function() {
if ($scope.userForm.$valid) {
// Form is valid
console.log('Submitted:', $scope.user);
}
};
CSS Classes
| Class | When Applied |
|---|---|
| ng-valid | Field is valid |
| ng-invalid | Field is invalid |
| ng-pristine | Not modified |
| ng-dirty | Modified by user |
Custom Validation
app.directive('uniqueEmail', function($q, $timeout) {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$asyncValidators.uniqueEmail = function(modelValue) {
var deferred = $q.defer();
$timeout(function() {
if (modelValue === 'taken@example.com') {
deferred.reject();
} else {
deferred.resolve();
}
}, 1000);
return deferred.promise;
};
}
};
});
Mini Practice
- Add validation attributes
- Display error messages
- Disable submit on invalid
- Create custom validators
Up Next
Continue with Select — working with selects.
Related Topics
Frequently Asked Questions about Validation
What is Validation in AngularJS?
Validation is a fundamental concept in AngularJS. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Validation?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Validation.
Why is Validation important in AngularJS?
Validation is essential for AngularJS development. Understanding this concept will help you write better code and solve real-world problems more effectively.