AngularJS Validations

The Angular Form has properties  which represent its state they are

  •    $pristine: Boolean true if the form/input has not been used yet.
  •    $dirty: Boolean true if the form/input has been used.
  •    $valid: The form content is valid
  •    $invalid: The form content is not valid.
  •    $submit: The form is submitted.

<! DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/
ajax/libs/angularjs/1.4.5/angular.min.js"></script>
</head>
<body ng-app="">
<form name="myform">
<div>First Name:<input name="myfName" 
ng-model="myfName" required>
<span ng-show="myform.myfName.$touched 
&& myform.myfName.$invalid">The First Name is required.</span></div>
<div>Last Name:<input name="mylName" 
ng-model="mylName" required>
<span ng-show="myform.mylName.$touched 
&& myform.mylName.$invalid">The Last Name is required.</span></div>
<div>Address:<input name="myAddress" 
ng-model=" myAddress " required>
</div>
</form>
</body>
</html>

 

1. How to write validation for Email?

<! DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/
ajax/libs/angularjs/1.4.5/angular.min.js"></script>
</head>
<body ng-app="">
<form name="myform">
<input type ="Email" name="emailInput" 
ng-model="emailInput" required>
</form>
<p>The input valid state:</p>
<h1>{{myform.emailInput.$valid}}</h1>
</body>
</html>

 

2. How to apply CSS classes?

CSS classes are added to forms and input fields depending on their state.

<! DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/
ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<style>
input.ng-invalid{background-color:lightgreen;}
input.ng-valid{background-color:peachpuff;}
</style>
</head>
<body ng-app="">
<form name="myform">
<input  name="textinput" 
ng-model=" textinput " required>
</form>
</body>
</html>