Number only validation in angularjs

Posted By : Pankaj Kumar Yadav | 22-Jun-2015

In this blog we will learn that how we can make a input text field validate for only number (the input field takes only number).
 Here are the steps: - 
 Step-1. Make an angular directive that take only numeric value to input.

 
myapp = angular.module("myapp", []);

myapp.directive('numbersOnly', function() {
   	return {
   		require: 'ngModel',
   		link: function(scope, element, attrs, modelCtrl) {
   			modelCtrl.$parsers.push(function(inputValue) {
   				if (inputValue == undefined) return ''
   				var onlyNumeric = inputValue.replace(/[^0-9]/g, '');
   				if (onlyNumeric != inputValue) {
   					modelCtrl.$setViewValue(onlyNumeric);
   					modelCtrl.$render();
   				}
   				return onlyNumeric;
   			});
   		}
   	};
   });

 

Step-2. Add this derective with your input field.
 For example - 

<input type="text" name="phoneNumber" ng-model="phoneNumber" numbers-only="numbers-only"/>


Now we can see that the input field 'phoneNumber' only takes numeric value.

Thanks

About Author

Author Image
Pankaj Kumar Yadav

Pankaj has been working as a Grails developer expertise in struts, spring, ejb, hibernate and angularjs framework.

Request for Proposal

Name is required

Comment is required

Sending message..