Javascript – Directive to allow only alphabetic characters in view and model value

angularjsangularjs-directivejavascriptregex

I am trying to achieve a directive that would be used to accept only alphabets into the text box i.e from a-z or A-z
I did try to do this by,

 angular.module('myApp', []).directive('alphabetsOnly', function(){
return {
 require: 'ngModel',
 link: function(scope, element, attrs, modelCtrl) {
   modelCtrl.$parsers.push(function (inputValue) {

       if (inputValue == undefined) return '' 
       var transformedInput = inputValue.replace(/^[a-zA-Z]+$/, ''); 
       if (transformedInput!=inputValue) {
          modelCtrl.$setViewValue(transformedInput);
          modelCtrl.$render();
       }         

       return transformedInput;         
   });
 }
};
});

function MyCtrl($scope) {
$scope.name = ''
}

but this does not works .

tried with pattern

'/^[a-zA-Z]$/' 

but no success. Can anyone help me with this.

Best Solution

You just need to move the caret ^ inside the brackets to negate letters, leaving everything else to be replaced. [^a-zA-Z]. You don't need the $ on the end either.

Here's an example of how to make a more reusable directive. You could use this for all kinds of things.

<input replace="[^a-zA-Z]" with="" ng-model="name">
.directive('replace', function() {
  return {
    require: 'ngModel',
    scope: {
      regex: '@replace',
      with: '@with'
    }, 
    link: function(scope, element, attrs, model) {
      model.$parsers.push(function(val) {
        if (!val) { return; }
        var regex = new RegExp(scope.regex);
        var replaced = val.replace(regex, scope.with); 
        if (replaced !== val) {
          model.$setViewValue(replaced);
          model.$render();
        }         
        return replaced;         
      });
    }
  };
})

If you wanted to use this replace directive, but used a particular formula often, you could keep your code DRY by making another directive that uses this one:

<input letters-only ng-model="name">
.directive('lettersOnly', function() {
  return {
    replace: true,
    template: '<input replace="[^a-zA-Z]" with="">'
  };
})