Validation:
Validation is a process of checking something against a standard.
AngularJS validation:
AngularJS provides client-side form validation. AngularJS provides the facility to get the current state of form and input fields.
Input States:
$untouched: The specified field has not been touched yet. Value can be true or false.
$touched: The specified field has been touched. Value can be true or false.
$pristine: The specified field has not been modified yet. Value can be true or false.
$dirty: The specified field has been modified. Value can be true or false.
$invalid: The specified field content is not valid. Value can be true or false.
$valid: The specified field content is valid. Value can be true or false.
Form States:
$pristine: No fields have been modified yet. Value can be true or false.
$dirty: One or more have been modified. Value can be true or false.
$invalid: The form content is not valid. Value can be true or false.
$valid: The form content is valid. Value can be true or false.
$submitted: The form is submitted. Value can be true or false.
Example Explanation:
First include the AngularJS library in the application. The ng-app directive initializes the application. We are validating name and email input fields here. For name field the ng-show directive show the error message if the field has been touched and is empty. For email field the ng-show directive show the error message if the field has been touched and not a valid email address.
Note: We have to use type=”email” in input element to specify that the value must be an email. In case of email the state of the input field is true before you start writing in it, even if it does not contain an e-mail address.
Example:
<!DOCTYPE html> <html> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"> </script> <body ng-app=""> <h1>AngularJS form validation example.</h1> <form name="myForm"> Name: <input name="myName" ng-model="myName" required> <span ng-show="myForm.myName.$touched && myForm.myName.$invalid">The name is required.</span> <br/><br/> Email: <input type="email" name="myEmail" ng-model="myEmail"> <span ng-show="myForm.myEmail.$touched && myForm.myEmail.$invalid">Invalid email.</span> </form> <p><strong>Input state (Name):</strong></p> <h1>{{myForm.myName.$valid}}</h1> <p><strong>Input state (Email):</strong></p> <h1>{{myForm.myEmail.$valid}}</h1> </body> </html> |