Hmahwish
Hmahwish

Reputation: 2232

Directive to allow only alphabetic characters in view and model value

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.

Upvotes: 1

Views: 15568

Answers (2)

Abijith Ajayan
Abijith Ajayan

Reputation: 274

Try with below Answer. 100% It will work.....

var app = angular.module('myApp', []);

(function() {

  app.directive('onlyLettersInput', onlyLettersInput);
  
  function onlyLettersInput() {
      return {
        require: 'ngModel',
        link: function(scope, element, attr, ngModelCtrl) {
          function fromUser(text) {
            var transformedInput = text.replace(/[^a-zA-Z]/g, '');
            //console.log(transformedInput);
            if (transformedInput !== text) {
              ngModelCtrl.$setViewValue(transformedInput);
              ngModelCtrl.$render();
            }
            return transformedInput;
          }
          ngModelCtrl.$parsers.push(fromUser);
        }
      };
    };

})();
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.14/angular.min.js"></script>
<link href="https://cdn.jsdelivr.net/foundation/5.5.0/css/foundation.css" rel="stylesheet"/>
<div ng-app="myApp">
  <div class="row">
    <div class="text-center"><h4>AngularJS Directive - only letters input</h4></div>
    <div class="small-8 small-centered columns panel">
      <form>
        <div class="row">
          <div class="small-3 columns">
            <label for="right-label" class="right inline">Only letters input</label>
          </div>
          <div class="small-9 columns">
            <input only-letters-input type="text" id="right-label" ng-model="myForm.onlyLetters">
          </div>
        </div>
      </form>
      <pre>myForm = {{myForm | json}}</pre>
    </div>
  </div>

Upvotes: 0

m59
m59

Reputation: 43745

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="">'
  };
})

Upvotes: 18

Related Questions