In AngularJS, validation logic can become repetitive if used across multiple forms. To avoid redundancy and improve maintainability, we can create a reusable validation directive. This directive can be used to validate inputs like email, phone numbers, passwords, etc.
1. Why Use a Custom Validation Directive?
Avoid duplicate validation logic in multiple forms.
Keep code clean, modular, and reusable.
Make validation rules consistent across the application.
Improve scalability by separating validation logic from the form.
2. Creating a Custom Directive for Password Strength
Requirement:
- A password field should be valid only if it meets strength criteria:
- At least 8 characters
- At least 1 uppercase letter
- At least 1 number
Step 1: Define the Directive
var app = angular.module('myApp', []);
app.directive('validatePassword', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$validators.strongPassword = function(value) {
var passwordRegex = /^(?=.*[A-Z])(?=.*\d).{8,}$/;
return passwordRegex.test(value);
};
}
};
});
Step 2: Use the Directive in the Form
<div ng-app="myApp" ng-controller="FormController">
<form name="userForm" novalidate>
<label>Password:</label>
<input type="password" name="password" ng-model="user.password" validate-password required>
<p ng-show="userForm.password.$error.strongPassword">❌ Password must have at least 8 characters, 1 uppercase letter, and 1 number.</p>
<button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>
</div>
How It Works?
✔ The directive uses $validators to check password strength.
✔ The validation error appears only if the password is weak.
✔ The submit button is disabled if the password is invalid.
3. Reusable Directive for Email Validation
Requirement:
- Validate that the input is a proper email format.
- Allow only example.com domain emails.
Step 1: Define the Directive
app.directive('validateEmail', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
ngModel.$validators.validEmail = function(value) {
var emailRegex = /^[a-zA-Z0-9._%+-]+@example\.com$/;
return emailRegex.test(value);
};
}
};
});
Step 2: Use the Directive in the Form
<label>Email:</label>
<input type="email" name="email" ng-model="user.email" validate-email required>
<p ng-show="userForm.email.$error.validEmail">❌ Enter a valid email (@example.com only).</p>
How It Works?
✔ The email format is validated using a regex pattern.
✔ Only example.com domain emails are allowed.
4. Custom Directive for Matching Passwords (Confirm Password)
🔹 Requirement:
- Ensure the confirm password field matches the original password.
Step 1: Define the Directive
app.directive('matchPassword', function() {
return {
require: 'ngModel',
scope: {
otherModelValue: '=matchPassword'
},
link: function(scope, element, attrs, ngModel) {
ngModel.$validators.match = function(value) {
return value === scope.otherModelValue;
};
scope.$watch('otherModelValue', function() {
ngModel.$validate();
});
}
};
});
Step 2: Use the Directive in the Form
<label>Password:</label>
<input type="password" name="password" ng-model="user.password" required>
<label>Confirm Password:</label>
<input type="password" name="confirmPassword" ng-model="user.confirmPassword" match-password="user.password" required>
<p ng-show="userForm.confirmPassword.$error.match">❌ Passwords do not match.</p>
How It Works?
✔ The confirm password field must match the first password.
✔ The directive watches for changes and revalidates dynamically.
5. Summary of Custom Validation Directives
Validation Type | Directive Name | Example Usage |
---|---|---|
Password Strength | validatePassword | <input validate-password> |
Email Format | validateEmail | <input validate-email> |
Match Password | matchPassword | <input match-password="user.password"> |