Form Validations using AngularJs

19 / Feb / 2015 by Sandeep Kumar 2 comments

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

FOUND THIS USEFUL? SHARE IT

comments (2)

Leave a Reply

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