From c104c2b2cdd19fe891c76e4a2b1f20d13e27369f Mon Sep 17 00:00:00 2001 From: Michael Benford Date: Wed, 9 Jul 2014 02:11:52 -0300 Subject: [PATCH] fix(tagsInput): Prevent an empty tag from being added Prevent an empty tag from being added when a certain combination of validation options allows it, which can also set the input as invalid in some cases. Closes #172 --- src/tags-input.js | 9 +++++---- test/tags-input.spec.js | 12 ++++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/src/tags-input.js b/src/tags-input.js index 5b1f7715..f254377f 100644 --- a/src/tags-input.js +++ b/src/tags-input.js @@ -40,7 +40,7 @@ tagsInput.directive('tagsInput', function($timeout, $document, tagsInputConfig) var self = {}, getTagText, setTagText, tagIsValid; getTagText = function(tag) { - return tag[options.displayProperty]; + return safeToString(tag[options.displayProperty]); }; setTagText = function(tag, text) { @@ -50,7 +50,8 @@ tagsInput.directive('tagsInput', function($timeout, $document, tagsInputConfig) tagIsValid = function(tag) { var tagText = getTagText(tag); - return tagText.length >= options.minLength && + return tagText && + tagText.length >= options.minLength && tagText.length <= options.maxLength && options.allowedTagsPattern.test(tagText) && !findInObjectArray(self.items, tag, options.displayProperty); @@ -65,7 +66,7 @@ tagsInput.directive('tagsInput', function($timeout, $document, tagsInputConfig) }; self.add = function(tag) { - var tagText = getTagText(tag).trim(); + var tagText = getTagText(tag); if (options.replaceSpacesWithDashes) { tagText = tagText.replace(/\s/g, '-'); @@ -77,7 +78,7 @@ tagsInput.directive('tagsInput', function($timeout, $document, tagsInputConfig) self.items.push(tag); events.trigger('tag-added', { $tag: tag }); } - else { + else if (tagText) { events.trigger('invalid-tag', { $tag: tag }); } diff --git a/test/tags-input.spec.js b/test/tags-input.spec.js index cf20c286..1ed7d39b 100644 --- a/test/tags-input.spec.js +++ b/test/tags-input.spec.js @@ -253,6 +253,18 @@ describe('tags-input directive', function() { { text: 'Item3' } ]); }); + + it('does not add an empty tag', function() { + // Arrange + compile('min-length="0"', 'allowed-tags-pattern=".*"'); + + // Act + newTag(''); + + // Assert + expect($scope.tags).toEqual([]); + expect(isolateScope.newTag.invalid).toBeFalsy(); + }); }); describe('focus outline', function() {