AngularJS Input Date Validation Transformation

AngularJS Input Date Validation Transformation

Below is an example of using Input with date validation and transformation. When you use date it’s mandatory to pass date object to the model otherwise Angular will throw exception. If invalid date object pass i.e. when getTime() method called and it returns NaN Angular rendered as empty string. Default time zone is always browser time zone.

  • Usage:
<input type="month"
       ng-model=""
       [name=""]
       [min=""]
       [max=""]
       [required=""]
       [ng-required=""]
       [ng-change=""]>
  • Example:  AngularJSDataAndValiation.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>AngularJS Input Date Validation Transformation</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> 
	var app = angular.module('monthExample', []);
	app.controller('DateController', [ '$scope', function($scope) {
		//$scope.value = new Date();		
	}]);	
	
</script>
</head>

<body data-ng-app="monthExample">

	<form name="myForm" data-ng-controller="DateController as dateCtrl">
		<hr>
		  Choose date in range between 2014 and 2015: 
		  <input id="exampleInput" type="date" name="input" data-ng-model="value" placeholder="yyyy-MM-DD" min="2014-01-01" max="2015-12-31" required />
		  <span class="error" data-ng-show="myForm.input.$error.required">Required!</span>
		  <span class="error" data-ng-show="myForm.input.$error.day">Not a valid month!</span>
		  value = {{value | date: "yyyy-MM-dd"}}
		  <p> Choose date: 
		  <input type="date" name="example2" data-ng-model="value2" required />
		  <span class="error" data-ng-show="myForm.input.$error.required">Required!</span></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>
		  <p>myForm.input.$error.month = {{myForm.input.$error.month}}</p>
		<hr>  
	</form>
</body>
</html>
  • Output:

AngularJS Input Date Validation Transformation AngularJS Input Date Validation Transformation

  • Test this code in Plunker here 

Leave a Reply

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