articles

home / developersection / articles / explain the custom validation in angularjs

Explain the Custom validation in AngularJS

Explain the Custom validation in AngularJS

Ashutosh Kumar Verma 794 23-Apr-2025

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


Updated 23-Apr-2025

Hi! This is Ashutosh Kumar Verma. I am a software developer at MindStick Software Pvt Ltd since 2021. I have added some new and interesting features to the MindStick website like a story section, audio section, and merge profile feature on MindStick subdomains, etc. I love coding and I have good knowledge of SQL Database.

Leave Comment

Comments

Liked By