Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Angular 1.x blacklisted characters (not allowed) validator.
(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
You can’t perform that action at this time.