Number only input in angular js - javascript

Number only input:
HTML
<input type="text" ng-model="employee.age" valid-input
input-pattern="[^0-9]+" placeholder="Enter an age" />
</label>
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
});
app.directive('validInput', function() {
return {
require: '?ngModel',
scope: {
"inputPattern": '#'
},
link: function(scope, element, attrs, ngModelCtrl) {
var regexp = null;
if (scope.inputPattern !== undefined) {
regexp = new RegExp(scope.inputPattern, "g");
}
if(!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (regexp) {
var clean = val.replace(regexp, '');
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
}
else {
return val;
}
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
}});
Why the above angularjs code so complicated? To have a number only text input can be done with normal javascript using regular expressions.
I wonder why such a lengthy code for angularjs being so famous?
Can't it be simpler than this?

Try the below approach, hope it works including the trim of white spaces,
<input type="text" ng-model="employee.age"
ng-pattern="^\d+$/|/[^\s*]/" placeholder="Enter an age" />

Related

How to edit an input value when it exceeds the limit using angularjs

<input id="myid" type="number" ng-model="maxVal" ng-change="maxValCheck()"
max="5" min="1" value="1"/>
in the controller
$scope.maxVal;
$scope.maxValCheck = function() {
if($scope.maxVal> 5) {
$scope.maxVal= 5;
}
}
I want to change the value of input field to 5 when it is more than 5.But it does not work. What am I doing wrong? And is there a better way you suggest to do this?
Better to use directive.
Example :
<input limit-to="5" type="number" ng-model="maxVal" >
app.directive("limitTo", [function() { return { restrict: "A", link: function(scope, elem, attrs) { var limit = parseInt(attrs.limitTo); angular.element(elem).on("keypress", function(e) { if (this.value > limit) e.preventDefault(); }); } } }]);

Angular material input number change format

In my angular-material app I have a field with validation:
<input type="number" ng-model="myValue"
name="myValue"
min="0" max="100"
ng-pattern="/^[0-9]\d*(\.\d+)?$/" required>
It works fine. But now I need to make it to allow user to type .75 and get instead of 0.75
So the question how to apply my filter:
if( myValue.substring(0,1) == "." ){
myValue = "0" + myValue;
}
before angular material ng-pattern and type="number" validation
You can write some directive with $filter, $formatters and $parsers:
app.directive('parser', ['$filter',
function($filter) {
return {
restrict:'A',
require: 'ngModel',
link: function(scope, element, attrs, ctrl) {
ctrl.$formatters.unshift(function (a) {
return $filter('myFilter')(ctrl.$modelValue)
});
ctrl.$parsers.unshift(function (viewValue) {
element[0].value = $filter('myFilter')(element[0].value);
return element[0].value;
});
}
};
}
]);
app.filter('myFilter', [
function() {
return function(input) {
if( input && input.substring(0,1) == "." ){
input = "0" + input;
}
return input;
};
}
]);
DEMO Plunkr
However you cannot use type number because as I remember . not supported and doesn't parses as integer
Hope it will give you direction

How to prevent input type="number" taking e [duplicate]

This question already has answers here:
Prevent the letter 'e' and dots from being typed in an input number
(2 answers)
Closed 6 years ago.
I had a text field of type="text" but it is allowing e to be entered ..I even want to prevent that happening how can we do that?
<input class="form-control" maxlength="12" ng-model="$ctrl.NumberInput" type="number"
min="0" required focus>
Can someone help!
You can use the following directive which will restrict only for numbers
app.directive('validNumber', function() {
return {
require: '?ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
if(!ngModelCtrl) {
return;
}
ngModelCtrl.$parsers.push(function(val) {
if (angular.isUndefined(val)) {
var val = '';
}
var clean = val.replace(/[^-0-9\.]/g, '');
var negativeCheck = clean.split('-');
var decimalCheck = clean.split('.');
if(!angular.isUndefined(negativeCheck[1])) {
negativeCheck[1] = negativeCheck[1].slice(0, negativeCheck[1].length);
clean =negativeCheck[0] + '-' + negativeCheck[1];
if(negativeCheck[0].length > 0) {
clean =negativeCheck[0];
}
}
if(!angular.isUndefined(decimalCheck[1])) {
decimalCheck[1] = decimalCheck[1].slice(0,2);
clean =decimalCheck[0] + '.' + decimalCheck[1];
}
if (val !== clean) {
ngModelCtrl.$setViewValue(clean);
ngModelCtrl.$render();
}
return clean;
});
element.bind('keypress', function(event) {
if(event.keyCode === 32) {
event.preventDefault();
}
});
}
};
});
DEMO
If you do not want to use directive use ng-pattern
<input type="text" ng-model="$ctrl.numberInput" ng-pattern="/[^0-9]/g" required />
DEMO
you can try the easiest way : ng-pattern
<input type="text" ng-model="$ctrl.numberInput" ng-pattern="/^\d+$/" required />

Input allow only 6 digits and after comma seperated and allow another 6 digits in angular js

Hi i am new to angularjs we want to implement a input text box which will allow only six digits and after entering six digits a comma separated will add and enter another six digits . Can you please help me. The sample code we have now is
**html**
<div ng-controller="MyCtrl">
<input type="text" ng-model="number" required="required" numbers-
only="numbers-only" />
</div>
Angular js controller
angular.module('myApp', []).directive('numbersOnly', function(){
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
if (inputValue == undefined) return ''
var transformedInput = inputValue.replace(/[^0-9]/g, '');
if (transformedInput!=inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
function MyCtrl($scope) {
$scope.number = ''
}
fiddler link we found
http://jsfiddle.net/thomporter/DwKZh/
have a look at ui-mask, set the mask as 999999-999999 or you can also use angular-input-mask
Edit your angular directive and bind a key press event to the textbox element. Inside the event check length. If length is 6 add a comma and rebind new value to your text box.
All you got to do is attach a key press event inside the directive link and check for input length and act accordingly. Instead of modifying your code, I pretty much wrote my own. Here is a DEMO
Here is the HTML code:
<div ng-app="myApp" ng-controller="MyCtrl">
<input type="text" ng-model="number" number-only required="required" />
</div>
Here is the modified directive code:
var app = angular.module('myApp', []);
app.controller('MyCtrl', ['$scope', function($scope) {
}])
app.directive('numberOnly', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
// Attach key press event
elem.bind('keypress', function(e) {
// Check if its a number
if (e.which >= 48 && e.which <= 57) {
var ar = scope.number.split(',');
if (ar[ar.length - 1].length >= 6) {
scope.number = scope.number + ',';
}
scope.$apply();
}
else {
e.preventDefault();
}
});
}
}
});

Custom directive for telephone format using angularjs

I am trying to write custom directive for USA telephone number using angularjs and need to preserve the data type of the field as integer.Here is the jsfiddle directive and need help to complete the directive.
If user enters a valid telephone no (exactly 10 numbers ie.1234567890) then input should split into 3 chunks as 123-456-7890 when the user moves to next control.otherewise I should show error message "not a valid number".
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myForm">
<input type="text" ng-model="telephone" phoneformat name="input1" />
<span class="error" ng-show="myForm.input1.$error.telephone">Numbers only!</span>
<span class="error" ng-show="myForm.input1.$error.telephone">Exact 10 Numbers only!</span>
</form>
</div>
var myApp = angular.module("myApp", []);
var myCtrl = myApp.controller("myCtrl",["$scope", function($scope) {
$scope.telephone = "1234567890";
}]);
myApp.directive("phoneformat", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attr, ngModelCtrl) {
var phoneformat = function () {
}
}
};
});
It looks like you want to leverage the $error property of the form to drive validation. To do this, you will need to call $setValidity in the ngModelCtrl that you have required into your directive:
var myApp = angular.module("myApp", []);
var myCtrl = myApp.controller("myCtrl",["$scope", function($scope) {
$scope.telephone = "1234567890";
}]);
myApp.directive("phoneformat", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, element, attr, ngModelCtrl) {
//Parsing is performed from angular from view to model (e.g. update input box)
//Sounds like you just want the number without the hyphens, so take them out with replace
var phoneParse = function (value) {
var numbers = value && value.replace(/-/g, "");
if (/^\d{10}$/.test(numbers)) {
return numbers;
}
return undefined;
}
//Formatting is done from view to model (e.g. when you set $scope.telephone)
//Function to insert hyphens if 10 digits were entered.
var phoneFormat = function (value) {
var numbers = value && value.replace(/-/g,"");
var matches = numbers && numbers.match(/^(\d{3})(\d{3})(\d{4})$/);
if (matches) {
return matches[1] + "-" + matches[2] + "-" + matches[3];
}
return undefined;
}
//Add these functions to the formatter and parser pipelines
ngModelCtrl.$parsers.push(phoneParse);
ngModelCtrl.$formatters.push(phoneFormat);
//Since you want to update the error message on blur, call $setValidity on blur
element.bind("blur", function () {
var value = phoneFormat(element.val());
var isValid = !!value;
if (isValid) {
ngModelCtrl.$setViewValue(value);
ngModelCtrl.$render();
}
ngModelCtrl.$setValidity("telephone", isValid);
//call scope.$apply() since blur event happens "outside of angular"
scope.$apply();
});
}
};
});
Working fiddle. This was just a quick way of demonstrating the parser and formatter pipelines that are used in ngModel, along with $setValidity -- which is used to populate the $error field(s).
Update: To use this same phone validation across multiple phones, use form with $error. Notice that each input gets a unique name that is used with myForm (name of form). Both use $error.telephone:
<form name="myForm">
Mobile Phone:
<input type="text" ng-model="mobilephone" phoneformat name="mobilephone" />
<span class="error" ng-show="myForm.mobilephone.$error.telephone">
Exact 10 Numbers only!
</span>
<br />
Home Phone:
<input type="text" ng-model="homephone" phoneformat name="homephone" />
<span class="error" ng-show="myForm.homephone.$error.telephone">
Exact 10 Numbers only!
</span>
</form>
Updated fiddle.
You might want to use http://angular-ui.github.io/ui-utils/ Mask directive.
Working Fiddle: http://jsfiddle.net/HB7LU/6581/
myApp.directive("phoneFormat", function () {
return {
restrict: "A",
link: function (scope, element, attr) {
element.bind('change', function() {
if ( this.value.length === 10 ) {
var number = this.value;
this.value = number.substring(0,3) + '-' + number.substring(3,6) + '-' + number.substring(6,10)
}
else {
document.querySelector('.helpblock').innerHTML = 'error in formatting';
}
});
}
};
});
Iv'e extended your original fiddle. here's the result:
http://jsfiddle.net/10k58awt/
You can find splittedNumber array (contains 3 parts of number) on form submission
js:
var myApp = angular.module("myApp", []);
var myCtrl = myApp.controller("myCtrl", ["$scope", function ($scope) {
$scope.telephone = "1234567890";
$scope.submit = function () {
var splittedNumber = [$scope.telephone.substring(0, 3), $scope.telephone.substring(3, 6), $scope.telephone.substring(6, 10)];
// Do something with splitted number
console.log(splittedNumber);
};
}]);
myApp.directive("phoneformat", function () {
return {
restrict: "A",
require: "ngModel",
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (phoneInput) {
phoneInput = phoneInput.trim();
if (phoneInput && phoneInput.length == 10 && !isNaN(phoneInput)) {
ctrl.$setValidity('phoneformat', true);
return phoneInput;
} else {
ctrl.$setValidity('phoneformat', false);
return undefined;
}
});
}
};
});
html:
<div ng-app="myApp" ng-controller="myCtrl">
<form name="myForm" novalidate ng-submit="myForm.$valid && submit()">
<input type="text" ng-model="telephone" phoneformat name="input1" /> <span class="error" ng-show="myForm.input1.$error.phoneformat">Invalid US Phone number!</span>
<div>
<button class="btn btn-primary" type="submit" ng-class="{'disabled': !myForm.$valid}">submit</button>
</div>
</form>
</div>

Categories

Resources