AngularJS has built-in validation (such as required
, email
,
minlength
, etc.), but custom validation allows you to,
- Define your own logic for input validation.
- Display custom error messages.
- Integrate with AngularJS's form validation conditions.
How Validation Works in AngularJS
Angular uses directives and validation conditions such as given below,
$valid
, $invalid
, $touched
, $dirty
, etc. You can create a
custom directive to plug your own validation logic into this system.
Example: Validate that a username does not contain spaces
<!DOCTYPE html>
<html ng-app="validationApp">
<head>
<title>Angular Custom Validation</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.8.2/angular.min.js"></script>
</head>
<body ng-controller="FormController">
<form name="userForm">
<label>Username:</label>
<input type="text" name="username" ng-model="username" no-space required />
<p ng-show="userForm.username.$error.required && userForm.username.$touched" style="color: red;">
Username is required.
</p>
<p ng-show="userForm.username.$error.noSpace" style="color: red;">
Username should not contain spaces.
</p>
</form>
<script>
var app = angular.module('validationApp', []);
app.controller('FormController', function($scope) {
$scope.username = '';
});
app.directive('noSpace', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
ctrl.$validators.noSpace = function(modelValue, viewValue) {
var value = modelValue || viewValue;
return value && value.indexOf(' ') === -1;
};
}
};
});
</script>
</body>
</html>
Summary
no-space
: Custom attribute directive
ctrl.$validators.noSpace
: Register a new validator
value.indexOf(' ') === -1;
: Return false
if space found.
userForm.username.$error.noSpace
: Error shown if validation fails
Also, read: Form Validation in Angularjs
Leave Comment