Form validation is essential for ensuring data integrity and enhancing user experience in web applications. AngularJS provides robust tools for form validation, making it easy to validate user input and manage form states. With features like built-in validators, custom validation options, and seamless error handling, AngularJS simplifies the process of building interactive and reliable forms.
In this guide, we’ll explore AngularJS form validation, its features, and practical implementation. Learn more about AngularJS and web development on The Coding College.
Key Features of AngularJS Form Validation
- Built-in Validators: Ready-to-use validators like
required
,email
,minlength
, andmaxlength
. - Custom Validators: Create your own validation rules for unique requirements.
- Validation States: Tracks input validity with properties like
$valid
,$invalid
,$touched
, and$pristine
. - Dynamic Error Messages: Show specific error messages for different validation errors.
How AngularJS Validates Forms
AngularJS automatically monitors form elements and applies validation states to inputs and forms. Validation feedback is provided using CSS classes, enabling developers to style inputs dynamically based on their state.
AngularJS Form States
$valid
: True if the input passes all validation rules.$invalid
: True if the input fails any validation rule.$pristine
: True if the input has not been modified.$dirty
: True if the input has been modified.$touched
: True if the input has been focused and blurred.
Basic Form Validation Example
<div ng-app="myApp" ng-controller="formCtrl">
<form name="userForm" ng-submit="submitForm()" novalidate>
<label>Username:</label>
<input type="text" name="username" ng-model="user.username" required>
<span ng-show="userForm.username.$touched && userForm.username.$invalid">Username 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 address.</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() {
if ($scope.userForm.$valid) {
alert('Form submitted successfully!');
}
};
});
</script>
Features:
- The
ng-submit
directive calls thesubmitForm()
function on form submission. - Error messages are displayed dynamically based on the validity of the inputs.
Built-In Validators in AngularJS
AngularJS provides several built-in validators for common use cases:
Validator | Description | Example Usage |
---|---|---|
required | Ensures the field is not empty. | <input required> |
email | Validates the email format. | <input type="email"> |
number | Ensures the input is a valid number. | <input type="number"> |
minlength | Specifies the minimum length of the input value. | <input minlength="3"> |
maxlength | Specifies the maximum length of the input value. | <input maxlength="10"> |
pattern | Matches the input value against a regular pattern. | <input pattern="\d{4}"> |
Custom Validators in AngularJS
If the built-in validators don’t meet your requirements, AngularJS allows you to create custom validators.
Example: Custom Validator for Password Strength
<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 an error if the password is less than 8 characters.
Dynamic Styling with CSS
AngularJS adds CSS classes based on the validation state of inputs.
CSS Class | Description |
---|---|
ng-valid | Applied when the field is valid. |
ng-invalid | Applied when the field is invalid. |
ng-pristine | Applied when the field hasn’t been modified. |
ng-dirty | Applied when the field has been modified. |
Example: Styling Invalid Inputs
<style>
input.ng-invalid.ng-touched {
border: 2px solid red;
}
</style>
Resetting the Form
To reset a form to its pristine state, AngularJS provides the $setPristine()
and $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: Resets the form and clears validation errors.
Best Practices
- Use Built-In Validators: For standard validation requirements.
- Add Custom Validators: For project-specific rules.
- Provide Clear Feedback: Show user-friendly error messages.
- Test Edge Cases: Ensure the form behaves correctly with unexpected input.
- Accessibility: Use proper labels and ARIA attributes for accessible forms.
Conclusion
AngularJS simplifies form validation, making it intuitive to validate user inputs and manage form states. Whether you use built-in validators or create custom ones, AngularJS empowers developers to create robust and user-friendly forms.