Form Validations using AngularJs
There are lots of ways to validate a web page like HTML5 validations, but why not do it in a better interactive way by using AngularJS. AngularJS provides us with several form properties for validation, which helps in providing instant feedback in case validation is violated.
$valid: return true when input field is valid.
$invalid: return true when input field is invalid.
$pristine: return true if input field has not been used yet.
$dirty: return true if input field has been used.
$error: Another useful property is the $error object that contains all of the validations on a particular form whether they are valid or invalid.
NOTE : The form must have a name associated with it to validate.
Before using angular validations, we need to disable default validations provided by HTML5. For this, add novalidate attribute in our form tag.
[js]
<form name="userForm" novalidate>
…
</form
[/js]
Some Angular directives also provides validation (i.e ngRequired, ngMaxlength, ngPattern, ngTrim, ngMinlength, etc).
Lets use ngClass directive to set CSS dynamically on invalid input field :
[js]
<div class="form-group">
<label for="uMobile">Mobile</label>
<input type="text" ng-model="uMobile" required ng-class="{ ‘has-error’ : userForm.uMobile.$invalid && !userForm.uMobile.$pristine }" class="form-control" id="uMobile" name="uMobile" ng-pattern="/^[0-9]+$/" ng-minlength="10" ng-maxlength="10" placeholder="Mobile Number">
…
</div>
[/js]
Then, we can also show the error message for each of our inputs if they are invalid or have already been used with ng-show directive.
[js]
<p ng-show="userForm.uMobile.$error.minlength" class="error">Mobile number is too short.</p>
<p ng-show="userForm.uMobile.$error.maxlength" class="error">Mobile number is too long.</p>
<p ng-show="userForm.uMobile.$error.pattern" class="error">Enter a numeric value</p>
[/js]
Atlast to disable submit button if our form is $invalid, ng-disabled is used .
[js]
<button type="submit" class="btn btn-info btn-primary" ng-disabled="userForm.$invalid"> Submit</button>
[/js]
So in this way we can make use of Angular validations for validating our webpages easily. For demo please visit my github page link .
Read Further on AngularJS Series
- AngularJS : A “Write Less Do More” JavaScript Framework
- AngularJS : Updating a Label Dynamically with User Input
- AngularJS : Adding Items to a JavaScript List and updating corresponding DOM Dynamically
- AngularJS : Text Suggestions
- AngularJS : Sorting objects on various attributes
- AngularJS : Fetching data from the server
- AngularJS : Multiple Views, Layout Template and Routing
- AngularJS : Implementing Routes And Multiple Views
- Building Intuitive Frontend Interfaces with AngularJS
Im obliged for the blog post.Really thank you! Really Great.
Im obliged for the blog post.Really thank you! Want more.