Tutorial 25 - Validation in angularjs.

Validation in angularjs.
AngularJS providers more attributes to help programer can validate form and controls in form easy. A form is valid when all of control in it to be valid.
The first we need to know about below property of angularjs:

$dirty: It means that user has interacted with the field.
$valid: It means that the field content is valid.
$invalid:  It means that the field content is invalid.
$pristine:  It means that user has not interacted with the field yet.

Ok follow this sample.



 <html>  
   <head>  
     <title>Angular JS Model</title>  
     <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>  
     <script>  
 var app = angular.module('myWebApp', []);  
 app.controller('validateCtrl', function($scope) {  
   $scope.id = '112';  
   $scope.username = 'Lewis';  
   $scope.email = 'Lewis@gmail.com';  
 });  
    </script>  
 <style>  
     .red {  
       padding: 20px;  
       background-color: red;  
       color: #FFF;  
     }  
     .my-input {  
       -webkit-transition: all linear 0.5s;  
       transition: all linear 0.5s;  
       background: transparent;  
     }  
     .my-input.ng-invalid {  
         color: white;  
         background: red;  
       }  
   </style>  
   </head>  
   <body ng-app="MyForm">  
 <h2>Validation Example</h2>  
 <form ng-app="myWebApp" ng-controller="validateCtrl"  
 name="mywebForm">  
 <p>ID:<br>  
  <input type="text" name="id" ng-model="id" ng-class="my-input" required >  
  <span ng-class="red" ng-show="myForm.id.$dirty && myForm.id.$invalid">  
  <span ng-show="myForm.id.$error.required">ID is required.</span>  
  </span>  
 </p>  
 <p>Username:<br>  
  <input type="text" name="user" ng-model="username" ng-class="my-input" required>  
  <span ng-class="red" ng-show="myForm.user.$dirty && myForm.user.$invalid">  
  <span ng-show="myForm.user.$error.required">Username is required.</span>  
  </span>  
 </p>  
 <p>Email:<br>  
  <input type="email" name="email" ng-model="email" ng-class="my-input" required>  
  <span ng-class="red" ng-show="myForm.email.$dirty && myForm.email.$invalid">  
  <span ng-show="myForm.email.$error.required">Email is required.</span>  
  <span ng-show="myForm.email.$error.email">Invalid email address.</span>  
  </span>  
 </p>  
 <p>  
  <input type="submit"  
  ng-disabled="myForm.user.$dirty && myForm.user.$invalid ||  
  myForm.email.$dirty && myForm.email.$invalid" value="Submit">  
 </p>  
   </body>  
  </html>  

You can change something on this sample to know how it works. That is a good way to learn.



1 comment:

Popular Posts