Reputation: 51
I want to create angular js directive for input field which will be configurable to allow numbers or alphabets or special character. Example
HTML
<input type="text" ng-model="ctrl.inputField" is-alphabets-allowed="false"
is-numbers-allowed="true"is-special-characters-allowed="false"
DIRECTIVE
angular.module('forms').directive('inputFieldConstraint', nputFieldConstraint);
InputFieldConstraint.$inject = ['constraintsService'];
function InputFieldConstraint(constraintsService) {
return {
restrict: 'EA',
require: 'ngModel',
scope: {
isAlphabetsAllowed: '=',
isNumbersAllowed: '=',
isSpecialCharactersAllowed: '='
},
link: function (scope, ele) {
$(ele).on('input', function () {
var test = $(ele).val().replace(/[^a-bA-Z]/g, '');
$(ele).val(test);
});
}
}
}
Please suggest best practice to create the directive and which regular expression I should use for these 3 cases?
Upvotes: 0
Views: 50
Reputation: 5188
Here's an approach - during the link()
, use the scope variables to build a single regex and then apply a new ng-pattern
directive programmatically:
link: function (scope, ele) {
const allowedClasses = [];
const { isAlphabetsAllowed, isNumbersAllowed, isSpecialCharactersAllowed } = scope;
if (isAlphabetsAllowed) allowedClasses.push("[a-zA-Z]");
if (isNumbersAllowed) allowedClasses.push("/d+");
if (isSpecialCharactersAllowed) allowedClasses.push("\\^\\$\\(\\)");
const regexString = allowedClasses.join("");
scope.regex = new RegExp(regexString, 'g');
$(ele).attr('ng-pattern', 'regex'); //references our new scope.regex
}
Note that you'd also need to update the value of scope.regex
if the isAlphabetsAllowed
etc ever changed, so you might need a $scope.watch()
or similar.
Also, in order to make sure that this operation happens before ng-pattern
directive fires, you'll need to ensure that the priority of your directive is higher than the priority of ng-pattern
, which is 0
, so I'd set the priority
to 1
to ensure you go first.
ng-pattern documentation: https://docs.angularjs.org/api/ng/directive/ngPattern
Upvotes: 1