2

I have a input text box and I would like to restrict the input to only alpha numerics (0-9, a-z, A-Z) and with max length of 15.

I am trying to acheive this in angularjs.

<input type="text" id="trackNumber" maxlength="15" ng-pattern="/^[a-zA-Z0-9]*$/" placeholder="" class="form-control" ng-model="trackNumber"/>

With "maxlength" set to 15, user cannot type 16th character in the box.

Similarly, when user types any special characters or white spaces, I would like to prevent "keypress" event. Currently, ng-pattern doesn't seem to stop user from typing invalid input.

How can do this?

Any help is greatly appreciated.

user3701057
  • 395
  • 1
  • 6
  • 22
  • 1
    As far as I know, this is not the expected behavior of `ng-pattern`. As a suggestion, I don't think it's expected behavior from a user's perspective either, so it might be frustrating or surprising to them. For example, what happens when a user pastes an invalid value into the field? – Shawn Bush Mar 10 '15 at 22:46
  • Thank you. We agreed to go with ng-pattern behavior with form validations. – user3701057 Mar 11 '15 at 23:28

1 Answers1

21

@Shawn Bush is correct this is not the default behaviour of ng-pattern.

However please see my plunk I have created a directive called "regExInput" which takes a required attribute "regEx" and checks this against each key stroke returning false if the entry is invalid according to the regular expression.

The code for the directive:

app.directive("regExInput", function(){
"use strict";
return {
    restrict: "A",
    require: "?regEx",
    scope: {},
    replace: false,
    link: function(scope, element, attrs, ctrl){
      element.bind('keypress', function (event) {
        var regex = new RegExp(attrs.regEx);
        var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
        if (!regex.test(key)) {
           event.preventDefault();
           return false;
        }
      });
    }
};
});

I hope this helps. Do not hesitate to ask for any refinements to the code :)

Also I borrowed the jQuery code from Dale's answer found here

Community
  • 1
  • 1
JDTLH9
  • 1,765
  • 1
  • 23
  • 34
  • Thank you for the directive. We agreed to go with ng-pattern behavior with form validations. – user3701057 Mar 11 '15 at 23:29
  • 2
    This actually works and you can use the ng-pattern attribute value as regexp input in the directive link. – A.W. Feb 29 '16 at 07:55