I have the following Angular directive that should capitalize the input and also reject any characters that are not English alphabet characters:
<input type="text" maxlength="1" capitalize />
.directive('capitalize', function() {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
var capitalize = function(inputValue) {
if (inputValue == undefined) inputValue = '';
inputValue = inputValue.replace(/[^a-zA-Z]/g, ''); //to reject non-alphabet characters
var capitalized = inputValue.toUpperCase();
if (capitalized !== inputValue) {
modelCtrl.$setViewValue(capitalized);
modelCtrl.$render();
}
return capitalized;
}
modelCtrl.$parsers.push(capitalize);
capitalize(scope[attrs.ngModel]); // capitalize initial value
}
};
})
It does capitalize the input, but does NOT reject non-alphabet characters. Suggestions?
Store your updated input value after removing special charters in a separate variable, and then capitalize it, so that the capitalized updated input value can be compared from the original value.
var charString = inputValue.replace(/[^a-zA-Z]/g, ''); //to reject non-alphabet characters
var capitalized = charString.toUpperCase();
updated JSFiddle here: http://jsfiddle.net/p149wuL1/3/ I hope this helps