ng-pattern for input type number

时间:2016-07-11 19:28:07

标签: javascript angularjs forms validation input

I have a jsbin --> https://jsbin.com/yipigicuve/edit?html,console,output

As per the link, i have the following code

<input ng-keypress="Num($event)" type="number" step=".1" ng-pattern="/^[+-]?(?:\d+\.?\d*|\d*\.?\d+)[\r\n]*$|^$/" ng-model="dataip"></>

$scope.Num = function (event) {
var keys = {
    'up': 38, 'right': 39, 'down': 40, 'left': 37,
    'escape': 27, 'backspace': 8, 'tab': 9, 'enter': 13, 'del': 46,
    '0': 48, '1': 49, '2': 50, '3': 51, '4': 52, '5': 53, '6': 54, '7': 55, '8': 56, '9': 57, 'dash':189, 'subtract':109
};
for (var index in keys) {
    if (!keys.hasOwnProperty(index)) continue;
    if (event.charCode == keys[index] || event.keyCode == keys[index]) {
        return; //default event
    }
}
event.preventDefault();
};

User enters alphabets and those are not accepted. There are certain alphanumeric keys which is accepted as shown in variable 'keys'

Certain patterns are presented so that null values, decimal point can be accepted.

My problem is....the current input type in the jsbin accepts values such as '-2.34---45' or '3.4...345"

It should accept decimal point and negative sign only once. i.e. '3.5566' or '-23.33'

Can someone let me know how to use ng-pattern to achieve my conditions.

2 个答案:

答案 0 :(得分:1)

Actually your ng -pattern is working correctly , ng -pattern just going to put the value of your model as undefined but visually you will not see anything, to do that you could use a filter and not allow a character that does not correspond with your pattern , or simply change some visual aspect of your input to notify that the value entered is incorrect

css (example):

  <style>
    .match{
      border-color:green;
    }

    .no-match{
      border-color:red;
    }

    input{
      outline:none;
    }
  </style>

html:

    <input ng-class="{'match':dataip, 'no-match':!dataip}" 
           ng-keypress="Num($event)"
           type="number" 
           step=".1" 
           ng-pattern="/^[+-]?(?:\d+\.?\d*|\d*\.?\d+)[\r\n]*$|^$/" 
           ng-model="dataip" />

  {{dataip}} <!--Print your model-->

With this approach you could code your filter or handle it with css

Note: this value is allowed 1.11. (dot at the end), check your pattern to avoid this behavior

I hope this answers your question

To know more about ngPattern, check the angular docs https://docs.angularjs.org/api/ng/directive/ngPattern

答案 1 :(得分:1)

您可以简化生活并使用已经完成的工作。

使用此指令:nksOnlyNumber

您可以根据您的要求设置输入。

这是代码段正在运行:

angular.module('app', [])
  .controller('mainCtrl', function($scope) {

  })
  .directive('nksOnlyNumber', function() {
    return {
      restrict: 'EA',
      require: 'ngModel',
      link: function(scope, element, attrs, ngModel) {
        scope.$watch(attrs.ngModel, function(newValue, oldValue) {
          var spiltArray = String(newValue).split("");

          if (attrs.allowNegative == "false") {
            if (spiltArray[0] == '-') {
              newValue = newValue.replace("-", "");
              ngModel.$setViewValue(newValue);
              ngModel.$render();
            }
          }

          if (attrs.allowDecimal == "false") {
            newValue = parseInt(newValue);
            ngModel.$setViewValue(newValue);
            ngModel.$render();
          }

          if (attrs.allowDecimal != "false") {
            if (attrs.decimalUpto) {
              var n = String(newValue).split(".");
              if (n[1]) {
                var n2 = n[1].slice(0, attrs.decimalUpto);
                newValue = [n[0], n2].join(".");
                ngModel.$setViewValue(newValue);
                ngModel.$render();
              }
            }
          }


          if (spiltArray.length === 0) return;
          if (spiltArray.length === 1 && (spiltArray[0] == '-' || spiltArray[0] === '.')) return;
          if (spiltArray.length === 2 && newValue === '-.') return;

          /*Check it is number or not.*/
          if (isNaN(newValue)) {
            ngModel.$setViewValue(oldValue || '');
            ngModel.$render();
          }
        });
      }
    };
  });
<!DOCTYPE html>
<html ng-app="app">

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

<body ng-controller="mainCtrl">
  <form name="form">
    <input type="text" nks-only-number ng-model="dataip" decimal-upto="6" />
  </form>
</body>

</html>