dagda1 dagda1 - 7 months ago 49
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?


you should use validators:

link: function(scope, elem, attrs, ctrl) {
   ctrl.$validators.isnumeric = function(modelValue, viewValue){
       return !isNaN(viewValue);