Created
April 18, 2017 16:03
-
-
Save replete/9bd63262228ce29020b6d7054119f47a to your computer and use it in GitHub Desktop.
Angular 1.x blacklisted characters (not allowed) validator.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function() { | |
'use strict'; | |
angular.module('shopperTrak.validators') | |
.directive('blacklistedCharacters', function (){ | |
return { | |
require: 'ngModel', | |
restrict:'A', | |
link: function(scope, elem, attrs, ngModel) { | |
var blacklistRegex = getBlacklistedRegex(attrs.blacklistedCharacters); | |
scope.$watch(attrs.blacklistedCharacters, function(){ | |
blacklistRegex = getBlacklistedRegex(attrs.blacklistedCharacters); | |
}); | |
// For DOM -> model validation | |
ngModel.$parsers.unshift(function(value) { | |
var valid = isValid(value); | |
ngModel.$setValidity('blacklistedCharacters', valid); | |
return valid ? value : undefined; | |
}); | |
//For model -> DOM validation | |
ngModel.$formatters.unshift(function(value) { | |
var valid = isValid(value); | |
ngModel.$setValidity('blacklistedCharacters', valid); | |
return value; | |
}); | |
function isValid(value) { | |
if (_.isString(value)) { | |
return !value.match(blacklistRegex) | |
} | |
} | |
function getBlacklistedRegex(value) { | |
// Presets: | |
switch (value) { | |
case 'special': return /[&<>"'\/%#*.()\`]/g; // JS special characters | |
} | |
if (_.isString(value)) value = value.split(''); | |
return RegExp('[' + value.join('') + ']', 'g'); | |
} | |
} | |
}; | |
}); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment