Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 846
Pawan Avatar asked Jan 07 '14 14:01

Pawan


People also ask

What is $setValidity in AngularJS?

The $setValidity() function is a built-in AngularJS function that is used to assign a key/value combination that can be used to check the validity of a specific model value. The key in this case is “unique” and the value is either true or false.

What is $dirty in AngularJS?

$dirty means the user has changed the input value, $invalid means the address itself is invalid. Therefore the error is only shown if the user has actively changed the input value to either an empty or invalid value.

How do you apply validations in AngularJS forms explain with proper example?

AngularJS performs form validation on the client-side. AngularJS monitors the state of the form and input fields (input, text-area, select), and notify the user about the current state. AngularJS also holds information about whether the input fields have been touched, modified, or not.


1 Answers

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);
      }
like image 181
Davin Tryon Avatar answered Oct 20 '22 19:10

Davin Tryon