1

Can't understand how to add ng-pattern that will mark field as invalid for all not valid entries.

I have tried to use this one "/^(0|\-?[1-9][0-9]*)$/ It works quite well with filtering numbers like 0.1 or even 0123 which are not valid (and not filtered out by /^-?[0-9][^\.]*$/ which was considered as right answer in some similar questions).

But actually it doesn't filter out numbers like "+3" and "1." (regex seems to be right and doesn't allow these values, i have tried to check it on regex101.com) If you use one of ng-patterns i listed here, try to enter +N into your input field. You will notice that it's valid. (might be that model will contain 3 & 1 instead of +3 & 1. but i would mark input as invalid anyway until user enters real integer number)

Hope anyone had the same problem.

By the way, one of possible solutions is to create directive that prevent ability to enter "." and "+" but i wonder whether it's possible to solve this problem with ng-pattern.

R3tep
  • 12,512
  • 10
  • 48
  • 75
Rantiev
  • 2,121
  • 2
  • 32
  • 56
  • Try Using This To Understand Regex https://regexper.com/ – Shankar Shastri Apr 29 '17 at 17:27
  • 1
    It seems you didn't read my qustion, i quite experienced to understand such simple regex. But problem is not inside regex but in ng-pattern most likely. Because it thinks 1. is still valid (if you test it by yourself in console with the same regex it's not valid) – Rantiev Apr 29 '17 at 19:42

1 Answers1

0

Try this ng-pattern="/^[1-9]\d*$/" to allow only integer numbers:

angular
  .module('App', [])
  .controller('DefaultController', ['$scope', '$log', function ($scope, $log) {
    $scope.logNumber = function() {
      $log.log($scope.num);
    };
  }]);
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.10/angular.min.js"></script>

<div ng-app="App">
  <div class="container" ng-controller="DefaultController">
    <form name="form">
      <input type="number" ng-pattern="/^[1-9]\d*$/" ng-change="logNumber()" ng-model="num" id="num"  name="num">
      <hr>
      Input valid? = <code>{{ form.num.$valid }}</code>
    </form>
  </div>
</div>
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46
  • 1
    Mmm the problem is that i want to have field marked as invalid when i enter "+4" or ".1" And as you can see it's valid in your example (model contains 4 & 1). How to disallow this? – Rantiev Apr 29 '17 at 19:47