I am currently diving deep into the world of AngularJS directives. My current project involves using a directive to prevent users from inputting special characters.
Below is the code snippet:
HTML
<input type="text" no-special-char ng-model="vm.customTag" class="form-control" value="" />
AngularJS Directive
app.directive('noSpecialChar', function () {
return {
require: 'ngModel',
restrict: 'A',
link: function (scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == null)
return ''
cleanInputValue = inputValue.replace(/[^\w\s]/gi, '');
if (cleanInputValue != inputValue) {
modelCtrl.$setViewValue(cleanInputValue);
modelCtrl.$render();
}
return cleanInputValue;
});
}
}
});
I have two requirements:
(1) I want to allow users to input a minus/dash '-'
character, which is currently not permitted by my regex /[^\w\s]/gi
. How can I modify it to allow the minus sign?
(2) The existing functionality only restricts special characters, but I also want to display a red alert message saying "special characters are not allowed" when a user attempts to input one. How can I achieve this additional feature?
Any guidance or assistance on these matters would be greatly appreciated!
Thank you