简体   繁体   中英

input type = number validation in angularjs

I am trying to validate < input type = number > by using input [number] directive of module ng of angularjs.

When using an input of type number, with the max (or min) attribute set to number such as

<input type=number min="20" max="40">

it works fine , but I my min and max data are coming data dynamically using ng-repeat such as

<input type=number min="configRow.valueStart" max="configRow.valueEnd"> , then it is not working .

I know that min and max only accept number and I am not much good in writing directives for that , Please help me any such directory or any suggestions would be appreciated.

min and max are expecting a value. So, this should work:

<input type=number min="{{configRow.valueStart}}" max="{{configRow.valueEnd}}">

Here is a plunker showing a demo. (this is just a modification of the documentation demo).

At the moment, the source for these attributes looks like below. So, you can see that a value is expected that is then cast to a float with parseFloat . So interpolating the model property {{}} to a value is required.

src/ng/directive/input.js

if (attr.min) {
        var minValidator = function(value) {
          var min = parseFloat(attr.min);
          return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value);
        };

        ctrl.$parsers.push(minValidator);
        ctrl.$formatters.push(minValidator);
      }

      if (attr.max) {
        var maxValidator = function(value) {
          var max = parseFloat(attr.max);
          return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value);
        };

        ctrl.$parsers.push(maxValidator);
        ctrl.$formatters.push(maxValidator);
      }

Max length will not work with <input type="number" the best way i know is to use oninput event to limit the maxlength, its a generic solution work with all the Javascript framework. Please see the below code.

<input name="somename"
    oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
    type = "number"
    maxlength = "6"
 />T

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM