Validating multiple fields dynamically

Loading

In AngularJS, you can validate multiple form fields dynamically using custom directives, watchers, and form controls like $valid, $invalid, $dirty, and $pristine. This approach is useful when you need to validate interdependent fields, such as password confirmation, matching values, or real-time validation based on user input.


1. Approaches for Dynamic Validation

There are multiple ways to validate multiple fields dynamically in AngularJS:

  1. Using $watch() – Monitor changes in multiple fields.
  2. Using $validators inside a custom directive – Create interdependent field validation.
  3. Using ngChange – Trigger validation as the user types.

2. Example: Password and Confirm Password Validation

Requirement: The Confirm Password field must match the Password field.

Step 1: Create the Directive

var app = angular.module('myApp', []);

app.directive('matchPassword', function() {
return {
require: 'ngModel',
scope: {
otherModelValue: "=matchPassword"
},
link: function(scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$validators.matchPassword = function(value) {
return value === scope.otherModelValue; // Valid if passwords match
};

scope.$watch("otherModelValue", function() {
ngModelCtrl.$validate();
});
}
};
});

Step 2: Use the Directive in the Form

<form name="passwordForm">
<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="passwordForm.confirmPassword.$error.matchPassword">
Passwords do not match.
</p>

<p ng-show="passwordForm.confirmPassword.$valid"> Passwords match.</p>
</form>

When passwords don’t match, an error appears.


3. Example: Validating Dependent Fields Dynamically

Requirement: Show an error if Email is entered but Phone is left empty.

Step 1: Use $watch() in Controller

app.controller('FormController', function($scope) {
$scope.$watchGroup(['user.email', 'user.phone'], function(newValues) {
var email = newValues[0];
var phone = newValues[1];

$scope.phoneRequired = email ? !phone : false;
});
});

Step 2: Implement the Dynamic Validation in the Form

<div ng-controller="FormController">
<form name="userForm">
<label>Email:</label>
<input type="email" name="email" ng-model="user.email">

<label>Phone:</label>
<input type="tel" name="phone" ng-model="user.phone" ng-required="phoneRequired">

<p ng-show="userForm.phone.$error.required">
Phone is required when Email is entered.
</p>
</form>
</div>

When the user enters an email, the phone field becomes required.


4. Example: Minimum Age Validation Based on Birthdate

Requirement: The user must be at least 18 years old based on the entered birthdate.

Step 1: Create the Directive

app.directive('minAge', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
ngModelCtrl.$validators.minAge = function(value) {
if (!value) return false;

var birthDate = new Date(value);
var today = new Date();
var age = today.getFullYear() - birthDate.getFullYear();

if (today.getMonth() < birthDate.getMonth() ||
(today.getMonth() === birthDate.getMonth() && today.getDate() < birthDate.getDate())) {
age--;
}

return age >= 18; // Valid if age is 18 or more
};
}
};
});

Step 2: Use It in the Form

<form name="ageForm">
<label>Birthdate:</label>
<input type="date" name="birthdate" ng-model="user.birthdate" min-age required>

<p ng-show="ageForm.birthdate.$error.minAge">
You must be at least 18 years old.
</p>

<p ng-show="ageForm.birthdate.$valid"> Age is valid.</p>
</form>

Users younger than 18 get an error message.


5. Summary Table

Validation CaseApproach Used
Password and Confirm PasswordCustom directive (matchPassword)
Email requires Phone$watchGroup() in Controller
Minimum Age RestrictionCustom directive (minAge)

Leave a Reply

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