dagda1 dagda1 - 1 year ago 142
AngularJS Question

Proper way to validate an input is numeric in angular

I have the following directive in angular:

define(function(require) {
var angular = require('angular');

angular.module('is-numeric', [])
.directive('isNumeric', [function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, elem, attrs, ctrl) {
elem.on('keyup', function(e) {
ctrl.$setValidity('isnumeric', !isNaN(e.target.value));

Do I really need to add an event handler for the keyup or is there a better way?

Answer Source

you should use validators:

link: function(scope, elem, attrs, ctrl) {
   ctrl.$validators.isnumeric = function(modelValue, viewValue){
       return !isNaN(viewValue);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download