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.

2
  • 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? Commented Mar 10, 2015 at 22:46
  • Thank you. We agreed to go with ng-pattern behavior with form validations. Commented Mar 11, 2015 at 23:28

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for the directive. We agreed to go with ng-pattern behavior with form validations.
This actually works and you can use the ng-pattern attribute value as regexp input in the directive link.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.