Diksha Dhakate
Diksha Dhakate

Reputation: 27

Input field with type number validation not working

Here is my code, I am trying to validated my input but validations not working

<form class="form-horizontal m-t-n" role="form">
 <div class="form-group">
    <div class="col-sm-4">
      <div class="input-group">
        <h3>{{ 'Select Quantity (max 5)' | translate }}</h3>
        <input type="number" name="quantity" ng-model="quantity" ng- change="setQuantity(quantity)" value="1"class="form-control" placeholder="{{ 'Quantity' | translate }}" ng-required integer >
      </div>
    </div>
 </div>     
</form><br>

Here is my setQuantity function:

$scope.setQuantity = function setQuantity( quantity ) {
    $scope.quantity = quantity;
}

Upvotes: 0

Views: 1113

Answers (1)

Aditya Bhave
Aditya Bhave

Reputation: 1028

You can check the validity manually using ng-form and $valid property. Make sure to give name to every field inside ng-form and access the field in controller using frmName[fieldName].

var app = angular.module('mainApp', []);
app.controller('MyController', ['$scope', function($scope) {
  $scope.setQuantity = function setQuantity(quantity) {
    let isValid = $scope.myFrm['quantity'].$valid;
    if (quantity && isValid) {
      $scope.quantity = quantity;
    }

    console.log(quantity, isValid);
  }
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="mainApp">
  <div ng-controller="MyController">
    <ng-form class="form-horizontal m-t-n" name="myFrm">
      <div class="form-group">
        <div class="col-sm-4">
          <div class="input-group">
            <h3>{{ 'Select Quantity (max 5)' }}</h3>
            <input type="number" name="quantity" ng-model="quantity" ng-change="setQuantity(quantity)" value="1" class="form-control" placeholder="{{ 'Quantity' }}" max="5" min="1" ng-required> </div>
        </div>
      </div>
    </ng-form>
  </div>
</div>

Make sure that the input field is inside a form tag. Also, you can simply use required html attribute instead of ng-required. Check below code.

<form>
  <input type="number" name="quantity" ng-model="quantity"
       ng-change="setQuantity(quantity)" min="1" max="5" value="1"
       class="form-control" placeholder="{{ 'Quantity' | translate }}"
       required integer>
  
  <br><br>
  
  <input type="submit" value="Submit">
</form>

If you Must use angular-js then keep ng-required, make sure to put the code inside ng-app

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

<div ng-app="">
  <form>
    <input type="number" name="quantity" ng-model="quantity"
         ng-change="setQuantity(quantity)" min="1" max="5" value="1"
         class="form-control" placeholder="{{ 'Quantity' }}"
         ng-required integer>

    <br><br>

    <input type="submit" value="Submit">
  </form>
</div>

Upvotes: 1

Related Questions