Creating custom validation directives

Loading

What You’ll Learn

What are custom validation directives?
How to create a custom validation directive in AngularJS
Example: Password strength validation
Example: Confirm password validation
Best practices for using custom validators


1️⃣ What are Custom Validation Directives?

AngularJS provides built-in validation (required, ng-pattern, email, etc.), but sometimes we need custom rules that these do not cover. Custom validation directives allow us to:
Apply complex validation logic (e.g., strong passwords)
Reuse the validation logic across multiple forms
Display custom error messages based on specific conditions


2️⃣ Creating a Custom Validation Directive

A directive is used to extend HTML functionality. A custom validator uses the ngModel controller to validate input.

Basic Structure of a Validation Directive

app.directive("customValidation", function () {
return {
require: "ngModel", // Requires ngModel for validation
link: function (scope, element, attrs, ngModel) {
ngModel.$validators.customValidation = function (value) {
// Custom validation logic
return value === "valid"; // Example condition
};
}
};
});

Explanation:
require: "ngModel" → Ensures the directive works with form inputs
ngModel.$validators.customValidation → Adds a custom validator


3️⃣ Example 1: Password Strength Validation

Let’s create a custom validator to check if a password contains at least one uppercase letter, one number, and one special character.

Password Strength Directive

app.directive("passwordStrength", function () {
return {
require: "ngModel",
link: function (scope, element, attrs, ngModel) {
ngModel.$validators.passwordStrength = function (value) {
// Password must contain at least one uppercase letter, one digit, and one special character
var regex = /^(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{6,}$/;
return regex.test(value); // Returns true if valid, false otherwise
};
}
};
});

🔹 Using the Directive in HTML

<form name="userForm">
<label>Password:</label>
<input type="password" name="password" ng-model="user.password" password-strength required />
<span ng-show="userForm.password.$error.passwordStrength">
Password must contain at least one uppercase letter, one number, and one special character.
</span>
</form>

How It Works?
If the password is weak, AngularJS marks it as invalid ($error.passwordStrength).
The error message appears only if the condition fails.


4️⃣ Example 2: Confirm Password Validation

Another common requirement is checking if two passwords match.

Confirm Password Directive

app.directive("matchPassword", function () {
return {
require: "ngModel",
scope: {
matchPassword: "=" // Get the password model to compare
},
link: function (scope, element, attrs, ngModel) {
ngModel.$validators.matchPassword = function (value) {
return value === scope.matchPassword; // Checks if passwords match
};

// Watch for changes in password field
scope.$watch("matchPassword", function () {
ngModel.$validate(); // Re-validate when password changes
});
}
};
});

Using the Directive in HTML

<form name="userForm">
<label>Password:</label>
<input type="password" ng-model="user.password" required />

<label>Confirm Password:</label>
<input type="password" name="confirmPassword" ng-model="user.confirmPassword" match-password="user.password" required />
<span ng-show="userForm.confirmPassword.$error.matchPassword">
Passwords do not match!
</span>
</form>

How It Works?
The directive compares passwords and marks the field as invalid if they don’t match.
$watch("matchPassword") ensures live validation when the password changes.

Leave a Reply

Your email address will not be published. Required fields are marked *