Custom Form Validation with AngularJS

Loading

Form validation is a crucial aspect of web applications to ensure data integrity and user-friendly interactions. AngularJS provides built-in validation directives like required, ng-minlength, and ng-pattern, but sometimes, we need custom validation to meet specific business requirements.


Topics Covered

  1. Why Use Custom Validation?
  2. Using ng-pattern for Simple Custom Validation
  3. Creating a Custom Directive for Validation
  4. Adding Validation Messages with ng-messages
  5. Complete Example with Custom Validation
  6. Conclusion

1. Why Use Custom Validation?

Built-in AngularJS validations cover many use cases, but custom validation is required for:

Validating usernames (e.g., only alphanumeric, no special characters)
Checking password strength (e.g., minimum one uppercase, one number)
Matching passwords in a registration form
Validating complex input formats like credit card numbers, license plate numbers, etc.


2. Using ng-pattern for Simple Custom Validation

AngularJS provides ng-pattern, which allows us to define regular expressions (regex) for validation.

Example: Validate Username (Only Alphanumeric Allowed)

<form name="userForm">
<label>Username:</label>
<input type="text" name="username" ng-model="user.username"
ng-pattern="/^[a-zA-Z0-9]+$/" required>
<span ng-show="userForm.username.$error.pattern">Invalid Username!</span>
</form>

How It Works:

Only allows letters and numbers.
Shows error message if validation fails.


3. Creating a Custom Directive for Validation

For complex validations, AngularJS allows us to create custom validation directives.

Example: Password Strength Validation

<form name="passwordForm">
<label>Password:</label>
<input type="password" name="password" ng-model="user.password" password-validator required>
<span ng-show="passwordForm.password.$error.strongPassword">Weak password!</span>
</form>

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

app.directive('passwordValidator', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$validators.strongPassword = function (value) {
return /^(?=.*[A-Z])(?=.*\d).{8,}$/.test(value); // At least 8 chars, 1 uppercase, 1 number
};
}
};
});
</script>

How It Works:

Defines a directive password-validator
Uses $validators to check if the password is strong
If validation fails, passwordForm.password.$error.strongPassword becomes true


4. Adding Validation Messages with ng-messages

AngularJS provides ng-messages for better error handling.

Example: Adding Validation Messages to a Form

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.8.2/angular-messages.min.js"></script>

<form name="emailForm">
<label>Email:</label>
<input type="email" name="email" ng-model="user.email" required>
<div ng-messages="emailForm.email.$error">
<span ng-message="required">Email is required.</span>
<span ng-message="email">Invalid email format.</span>
</div>
</form>

Uses ng-messages to display multiple validation errors dynamically.
Improves user experience with clear error messages.


5. Complete Example with Custom Validation

Here’s a full-fledged form with:
Custom password strength validation
Confirm password validation
Error messages using ng-messages

<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.8.2/angular-messages.min.js"></script>
</head>
<body ng-controller="FormController">

<form name="registerForm" ng-submit="submitForm()">

<label>Password:</label>
<input type="password" name="password" ng-model="user.password" password-validator required>
<div ng-messages="registerForm.password.$error">
<span ng-message="required">Password is required.</span>
<span ng-message="strongPassword">Password must be at least 8 characters, 1 uppercase, and 1 number.</span>
</div>

<label>Confirm Password:</label>
<input type="password" name="confirmPassword" ng-model="user.confirmPassword" match-password="user.password" required>
<div ng-messages="registerForm.confirmPassword.$error">
<span ng-message="required">Confirm Password is required.</span>
<span ng-message="passwordMatch">Passwords do not match.</span>
</div>

<button type="submit">Register</button>
</form>

<script>
var app = angular.module('myApp', ['ngMessages']);

app.controller('FormController', function ($scope) {
$scope.user = {};
$scope.submitForm = function () {
alert("Form submitted successfully!");
};
});

app.directive('passwordValidator', function () {
return {
require: 'ngModel',
link: function (scope, element, attrs, ctrl) {
ctrl.$validators.strongPassword = function (value) {
return /^(?=.*[A-Z])(?=.*\d).{8,}$/.test(value);
};
}
};
});

app.directive('matchPassword', function () {
return {
require: 'ngModel',
scope: {
otherModelValue: '=matchPassword'
},
link: function (scope, element, attrs, ctrl) {
ctrl.$validators.passwordMatch = function (value) {
return value === scope.otherModelValue;
};

scope.$watch('otherModelValue', function () {
ctrl.$validate();
});
}
};
});
</script>

</body>
</html>

Leave a Reply

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