Reputation: 601
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" />
Upvotes: 1
Views: 623
Reputation: 24874
You can do it using:
I made this snippet showing both ways:
(function() {
"use strict";
angular.module('app', ['ngMask'])
.controller('mainCtrl', function($scope) {
$scope.checkNumber = function() {
$scope.input = $scope.input.replace(/\D+/, '');
}
})
})();
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ngMask/3.1.1/ngMask.min.js"></script>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body ng-controller="mainCtrl">
<form name="form" novalidate>
<label for="withoutMask">Input without mask: </label>
<input type="text" id="withoutMask" ng-model="input" ng-change="checkNumber()">
<hr>
<label for="mask">Input with mask: </label>
<input type="text" id="mask" mask="d" repeat="15" restrict="reject" limit="false" ng-model="otherInput">
</form>
</body>
</html>
Upvotes: 1
Reputation: 1546
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.
Upvotes: 1
Reputation: 6813
why not use the built-in HTML support?
<input type="number">
supported - http://caniuse.com/#search=input%20type%3D%22number%22
Upvotes: 0