1window.angular && (function(angular) {
2  'use strict';
3
4  /**
5   * Username validator
6   *
7   * Checks if entered username is a duplicate
8   * Provide existingUsernames scope that should be an array of
9   * existing usernames
10   *
11   * <input username-validator  existing-usernames="[]"/>
12   *
13   */
14  angular.module('app.accessControl')
15      .directive('usernameValidator', function() {
16        return {
17          restrict: 'A', require: 'ngModel', scope: {existingUsernames: '='},
18              link: function(scope, element, attrs, controller) {
19                if (scope.existingUsernames === undefined) {
20                  return;
21                }
22                controller.$validators.duplicateUsername =
23                    (modelValue, viewValue) => {
24                      const enteredUsername = modelValue || viewValue;
25                      const matchedExisting = scope.existingUsernames.find(
26                          (username) => username === enteredUsername);
27                      if (matchedExisting) {
28                        return false;
29                      } else {
30                        return true;
31                      }
32                    };
33                element.on('blur', () => {
34                  controller.$validate();
35                });
36              }
37        }
38      });
39})(window.angular);
40