CraZyDroiD
CraZyDroiD

Reputation: 7105

Allow dashes for alphanumeric directive in angularjs

I'm using a directive to allow only alphanumeric characters in my fields. I found this directive to do this:

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

This works fine. Now I want to allow dashes as well. How can i do this?

Upvotes: 2

Views: 2024

Answers (1)

Kalhan.Toress
Kalhan.Toress

Reputation: 21901

change you regular expression to

 text.replace(/[^0-9a-zA-Z\-\s]/g, '');

Example

Upvotes: 2

Related Questions