summaryrefslogtreecommitdiffstats
path: root/app/access-control/directives/username-validator.js
blob: 395e635c47b145ddc5fbaa0d455c35e9397b309f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
window.angular && (function(angular) {
  'use strict';

  /**
   * Username validator
   *
   * Checks if entered username is a duplicate
   * Provide existingUsernames scope that should be an array of
   * existing usernames
   *
   * <input username-validator  existing-usernames="[]"/>
   *
   */
  angular.module('app.accessControl')
      .directive('usernameValidator', function() {
        return {
          restrict: 'A', require: 'ngModel', scope: {existingUsernames: '='},
              link: function(scope, element, attrs, controller) {
                if (scope.existingUsernames === undefined) {
                  return;
                }
                controller.$validators.duplicateUsername =
                    (modelValue, viewValue) => {
                      const enteredUsername = modelValue || viewValue;
                      const matchedExisting = scope.existingUsernames.find(
                          (username) => username === enteredUsername);
                      if (matchedExisting) {
                        return false;
                      } else {
                        return true;
                      }
                    };
                element.on('blur', () => {
                  controller.$validate();
                });
              }
        }
      });
})(window.angular);
OpenPOWER on IntegriCloud