</>
Skip to content
AngularJS lessons (13/28)

AngularJS — Validation

Built-in Validators

AttributeDescription
requiredField required
ng-minlengthMinimum length
ng-maxlengthMaximum length
ng-patternRegex pattern
emailEmail format
numberNumber format

Validation Example

<form name="userForm" ng-submit="submitForm()">
  <input name="name" ng-model="user.name" required ng-minlength="3">
  <span ng-show="userForm.name.$error.required">Name is required</span>
  <span ng-show="userForm.name.$error.minlength">Minimum 3 characters</span>
  
  <input name="email" ng-model="user.email" required email>
  <span ng-show="userForm.email.$error.required">Email is required</span>
  <span ng-show="userForm.email.$error.email">Invalid email</span>
  
  <button type="submit" ng-disabled="userForm.$invalid">Submit</button>
</form>

Validation States

$scope.submitForm = function() {
  if ($scope.userForm.$valid) {
    // Form is valid
    console.log('Submitted:', $scope.user);
  }
};

CSS Classes

ClassWhen Applied
ng-validField is valid
ng-invalidField is invalid
ng-pristineNot modified
ng-dirtyModified by user

Custom Validation

app.directive('uniqueEmail', function($q, $timeout) {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModel) {
      ngModel.$asyncValidators.uniqueEmail = function(modelValue) {
        var deferred = $q.defer();
        $timeout(function() {
          if (modelValue === 'taken@example.com') {
            deferred.reject();
          } else {
            deferred.resolve();
          }
        }, 1000);
        return deferred.promise;
      };
    }
  };
});

Mini Practice

  1. Add validation attributes
  2. Display error messages
  3. Disable submit on invalid
  4. Create custom validators

Up Next

Continue with Select — working with selects.

Related Topics

Frequently Asked Questions about Validation

What is Validation in AngularJS?

Validation is a fundamental concept in AngularJS. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Validation?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Validation.

Why is Validation important in AngularJS?

Validation is essential for AngularJS development. Understanding this concept will help you write better code and solve real-world problems more effectively.