0

I have this following html code. I donot want the decimal point to be there in this input field.

can someone let me know how to achieve this.

 <input type="number" min="0" step="1" ng-pattern="/^(0|[1-9][0-9]*)$/" ng-model="params.data" />
Patrick
  • 3,938
  • 6
  • 20
  • 32
  • Possible duplicate of [javascript regular expression to not match a word](http://stackoverflow.com/questions/6449131/javascript-regular-expression-to-not-match-a-word) – Spencer Wieczorek Jul 22 '16 at 21:03
  • What about running a function after focus has been taken away? They enter 093.4 and go to the next input. The function then returns 093 – austinthedeveloper Jul 22 '16 at 21:04
  • yea, that would work too. can you please show me a link for that. – Patrick Jul 22 '16 at 21:05
  • This may be what you're looking for - https://jsfiddle.net/lancelarsen/Tx7Ty/ Just change the "setDecimal" value to "0". – Josh Jul 22 '16 at 21:05
  • Or just add to `ngPattern` so the regexp does not include `.`. See the duplicate and replace the `abc|def` with `\.` – Spencer Wieczorek Jul 22 '16 at 21:06
  • @SpencerWieczorek- i got confused there – Patrick Jul 22 '16 at 21:07
  • `ngPattern` does nothing besides validate the field in a form, it still allows you to type a decimal point even if your regex doesn't match. To achieve what you want you need a `directive | mask | ngKeyPress` – developer033 Jul 22 '16 at 21:38

1 Answers1

1

Please, keep in mind that ngPattern is just used to validate the field in a form (formName.field.$error.pattern), it still allows you to type a decimal point or whatever even if your regex doesn't match.

You can do it using:

  1. ngChange directive;
  2. ngMask module (Always I need handle inputs with masks I use it).

I made this snippet showing both ways:

(function() {
  "use strict";
  angular
    .module('app', ['ngMask'])
    .controller('mainCtrl', mainCtrl);

  function mainCtrl($scope) {
     $scope.params = {};
     $scope.checkNumber = function() {
       if ($scope.params.data) {
         $scope.params.data = $scope.params.data.replace(/\D+/, '');
       }
     }
  }
})();
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/ngMask/3.1.1/ngMask.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <form name="form" novalidate>
    <label for="withoutMask">Input without mask: </label>
     <input type="text" id="withoutMask" ng-model="params.data" ng-change="checkNumber()">
    <hr>
    <label for="mask">Input with mask: </label>
    <input type="text" id="mask" mask="d" repeat="15" restrict="reject" limit="false" ng-model="otherInput">
  </form>
</body>

</html>

I hope it helps!

developer033
  • 24,267
  • 8
  • 82
  • 108