0

I,m trying to create simple custom directive in angularJS which validates if user types in an an integer or not.

If the user enters an integer then an error message should appear in the bottom that "integers are not allowed".

Any idea how can i achieve this...? (A fiddle would be awesome)

and also...

Is this possible to do WITHOUT using $scope.$watch ?

Is this a professional and effective way to check for client side input validation ? (does this approach compromises performance of the application) ?

2 Answers 2

1

You can use ng-pattern to validate if it is a valid number or not. Other way is as you asked , create a custom directive. I am going with notNumber name, it can be isNumber as well with small change.

angular.module('app')
  .directive('notNumber', notNumber);

function notNumber() {
  return {
    require: 'ngModel',
    link: function(scope, elem, attr, ctrl) {
      ctrl.$formatters.unshift(function(value) {
        if (value) {
          ctrl.$setValidity('notNumber', Number.isNaN(value));
        }
        return value;
      });
    }
  };
}

In HTML,

<input type="text" ng-model="model" not-number />
Sign up to request clarification or add additional context in comments.

1 Comment

Nope...the code is not working...i don't see any error if user types an integer...can you please make a fiddle ?
0

Simpler than you might have expected.... use ng-pattern

<input type="text" ng-model="model" ng-pattern="\\d+" />

The demo in docs link above is set to this same pattern as default.

As for doing this...of course, providing user feedback live in form is normal. It doesn't alleviate doing server side validation though which must be done

1 Comment

Nope...the code is not working...i don't see any error if user types an integer...can you please make a fiddle ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.