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
More From Oodles
Ready to innovate? Let's get in touch
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Pankaj Kumar Yadav
Pankaj has been working as a Grails developer expertise in struts, spring, ejb, hibernate and angularjs framework.