- Angular JS Tutorial
- AngularJS Home
- AngularJS Introduction
- AngularJS Expressions
- AngularJS Directives
- AngularJS Modules
- AngularJS Controllers
- AngularJS Scopes
- AngularJS Data Binding
- AngularJS Services
- AngularJS HTTP
- AngularJS Filters
- AngularJS Forms
- AngularJS Validation
- AngularJS DOM Manipulation
- AngularJS Select
- AngularJS Tables
- AngularJS Events
- AngularJS Routing
- AngularJS Includes
- AngularJS Animations
- AngularJS Dependency Injection
- AngularJS API
- AngularJS Deployment
AngularJS Validation
AngularJS Validation is a powerful feature that ensures the integrity of data before it ever reaches your server. Instead of writing complex JavaScript to manually check every input field, AngularJS provides a declarative way to handle form validation directly in your HTML. This creates a smoother user experience by providing immediate feedback as users type.
Key Features of AngularJS Validation
- Real-Time Validation: AngularJS uses data-binding to validate fields instantly as the user interacts with the form, rather than waiting for a "Submit" button click.
- Built-In Validators: It leverages standard HTML5 attributes like
required,minlength, andpattern, but adds logic to track their state. - Custom Validators: For unique business logic (like checking if a username is already taken), you can write custom directives.
- State Management: AngularJS tracks whether a form is "dirty" (touched), "pristine" (untouched), or "invalid" automatically.
- CSS Integration: It automatically adds and removes CSS classes (like
.ng-invalidor.ng-dirty) to your elements, making it easy to style error states.
Common Built-In Validators
AngularJS augments standard HTML5 input types to provide robust validation out of the box. Here are the most frequently used validators:
- required: The field must contain a value.
- minlength / maxlength: Limits the character count of the input.
- pattern: Uses a Regular Expression (Regex) to validate the input format.
- email: Checks for a valid email structure (e.g., [email protected]).
- number: Ensures only numeric values are entered.
Example: Built-In Validation
<form name="registrationForm" novalidate>
<div>
<label>Email Address:</label>
<input type="email" name="userEmail" ng-model="user.email" required>
<!-- Error messages only show if the field has been modified ($dirty) -->
<div ng-if="registrationForm.userEmail.$dirty">
<span ng-show="registrationForm.userEmail.$error.required">Email is required.</span>
<span ng-show="registrationForm.userEmail.$error.email">Please enter a valid email address.</span>
</div>
</div>
</form>
novalidate attribute to your <form> tag. This prevents the browser's default validation tooltips from interfering with your custom AngularJS error messages.
State Tracking in Validation
One of the most useful features of AngularJS forms is the ability to track the "state" of an input. Each form and input field is assigned an object that includes several boolean properties:
- $pristine: True if the user has not yet interacted with the field.
- $dirty: True if the user has modified the field.
- $valid: True if all validation rules for that field are satisfied.
- $invalid: True if one or more validation rules have failed.
- $touched: True if the user has blurred (left) the field, regardless of whether they changed the value.
$dirty or $touched to ensure you only show errors after the user has actually interacted with the field.
Example: State-Based Styling
<style>
input.ng-invalid.ng-dirty { border: 2px solid red; }
input.ng-valid.ng-dirty { border: 2px solid green; }
</style>
<input type="text" name="username" ng-model="user.username" required>
Custom Validation
Standard validators cover most needs, but sometimes you need custom logic—for example, verifying that two passwords match or that a value falls within a dynamic range. To do this, you create a custom directive that interacts with ngModelController.
Example: Custom Age Validator
app.directive('minAge', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
// Add a custom validator to the $validators object
ngModel.$validators.minAge = function(modelValue, viewValue) {
var value = modelValue || viewValue;
// Logic: Return true if valid, false if invalid
return parseInt(value) >= 18;
};
}
};
});
Usage:
<input type="number" name="userAge" ng-model="user.age" min-age>
<span ng-show="myForm.userAge.$error.minAge">You must be at least 18 years old to register.</span>
Handling Form Errors
The $error object is a key-value store where the key is the name of the validator (like required or minlength) and the value is a boolean indicating if that specific error is currently active.
Example: Detailed Error Feedback
<form name="passwordForm">
<label>New Password:</label>
<input type="password" name="pwd" ng-model="user.pwd" ng-minlength="8" required>
<div class="error-container" ng-show="passwordForm.pwd.$dirty && passwordForm.pwd.$invalid">
<small ng-show="passwordForm.pwd.$error.required">Password cannot be empty.</small>
<small ng-show="passwordForm.pwd.$error.minlength">Password must be at least 8 characters long.</small>
</div>
</form>
Submitting Validated Forms
In a professional application, you should prevent the form from submitting if any data is invalid. You can do this by checking the $invalid property of the entire form.
Example: Conditional Submission
<form name="checkoutForm" ng-submit="processOrder()" novalidate>
<input type="text" name="address" ng-model="order.address" required>
<!-- Disable button until the entire form is valid -->
<button type="submit" ng-disabled="checkoutForm.$invalid" class="btn-submit">
Complete Purchase
</button>
</form>
<script>
app.controller('CheckoutController', function($scope) {
$scope.processOrder = function() {
// Double-check validity in the controller for safety
if ($scope.checkoutForm.$valid) {
console.log('Order processed for: ', $scope.order.address);
}
};
});
</script>
Summary
AngularJS Validation takes the pain out of form handling by providing a structured way to monitor user input. By combining built-in validators with custom directives and state-tracking properties like $dirty and $invalid, you can build forms that feel responsive, professional, and robust. Remember to always provide clear feedback to your users and never skip server-side validation.