Steve Gaines Steve Gaines - 3 months ago 13x
AngularJS Question

Why won't this ng-pattern filter numbers?

I have an AngularJS single page application. One view has a textbox that I want to only accept numbers for an integer field. I have entered this code in the controller and this textbox in the view, but when I run the view it accepts any keyboard characters. Can you tell me how I need to modify this to work?

$scope.FilterNumbersOnly = /^\d+$/;

<input ng-model="x.COLUMN_VALUE" ng-pattern="FilterNumbersOnly" />


From the AngularJS documentation, ng-pattern will set the pattern key on the error object when the values input into the text-based field do not pass the specified regex test.

This says nothing about prohibiting users from inputting text. If you would like to add that behavior, you need to listen to the pattern key on the error object and attach handlers to it. When the input is invalid, the error object will reflect this, and you should respond by preventing user input. Or you can take whatever such action you deem necessary.

To prevent user input, you can set the disabled attribute on the input field when the pattern key on the error object is set.

One simple way to accomplish this is with the ng-if directive.

<input disabled ng-if="!form.input.$valid" />
<input ng-if="form.input.$valid" />

Here is a link to a working example.