AngularJS Form Input Number Validation

AngularJS Form Input Number Validation

If you want to do validation of entered input number inside AngularJS form before submitting page please have below sample html page with from with one input field of type number where we are checking of value entered in input box is valid or not:

  • AngularJSNumberValiation.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AngularJS form with input number</title>
<style type="text/css">
.error {
  color: red;
  font-size:1.1em;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.3/angular.min.js"></script>
<script type="text/javascript">
	var value = element(by.binding('value'));
	var valid = element(by.binding('myForm.input.$valid'));
	var input = element(by.model('value'));
	
</script>
</head>
<body data-ng-app="formWithNumber">
  <script>
  angular.module('formWithNumber', [])
    .controller('NumberController', ['$scope', function($scope) {
      $scope.value = 50;
    }]);
</script>
<form name="myForm" data-ng-controller="NumberController">
  
  Number: <input type="number" name="input" data-ng-model="value" min="0" max="9999" required>
  <span class="error" data-ng-show="myForm.input.$error.required">Required!</span>
  <span class="error" data-ng-show="myForm.input.$error.number">Not valid number!</span>
  
  <p>value = {{value}}</p>
  <p>myForm.input.$valid = {{myForm.input.$valid}}</p>
  <p>myForm.input.$error = {{myForm.input.$error}}</p>
  <p>myForm.$valid = {{myForm.$valid}}</p>
  <p>myForm.$error.required = {{!!myForm.$error.required}}</p>
 </form>
</body>
</html>
  • Output:

AngularJS Form Input Number Validation

AngularJS Form Input Number Validation

  • Test this code in Plunker here

Leave a Reply

Your email address will not be published. Required fields are marked *