Yoshie Muranaka | fa56273 | 2019-07-17 11:23:15 -0500 | [diff] [blame^] | 1 | window.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.users').directive('usernameValidator', function() { |
| 15 | return { |
| 16 | restrict: 'A', require: 'ngModel', scope: {existingUsernames: '='}, |
| 17 | link: function(scope, element, attrs, controller) { |
| 18 | if (scope.existingUsernames === undefined) { |
| 19 | return; |
| 20 | } |
| 21 | controller.$validators.duplicateUsername = |
| 22 | (modelValue, viewValue) => { |
| 23 | const enteredUsername = modelValue || viewValue; |
| 24 | const matchedExisting = scope.existingUsernames.find( |
| 25 | (username) => username === enteredUsername); |
| 26 | if (matchedExisting) { |
| 27 | return false; |
| 28 | } else { |
| 29 | return true; |
| 30 | } |
| 31 | }; |
| 32 | element.on('blur', () => { |
| 33 | controller.$validate(); |
| 34 | }); |
| 35 | } |
| 36 | } |
| 37 | }); |
| 38 | })(window.angular); |