Learn by easy steps

Ajs Validation


1. Create a simple form using bootstrap or without bootstrap.

<!doctype html>
<html ng-app>
<meta charset="utf-8">
<title>Form validation using Angularjs</title>
<script src="angular.js"></script>
<link href="bootstrap.css" rel="stylesheet" />
<link href="bootstrap-theme.css" rel="stylesheet" />
<form style="width:60%" name="custForm" novalidate>
<h2 align="center">Customer Entry Form</h2><br>
<div class="well">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" name="name" class="form-control" required>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" name="email" class="form-control" required>
<div class="form-group">
<label for="contact">Contact No:</label>
<input type="text" name="contact" class="form-control" required>
<div class="form-group">
<label for="gender">Gender:</label>
<select name="gender" class="form-control" required>
<div class="checkbox">
<input type="checkbox" name="regular " >
Regular Customer
<div class="text-center">
<input type="button" class="btn btn-primary" value="Submit">

2. Add ng-model directive for each form field and ng-disabled for button.

3. Add style code to indicate valid or invalid field.

input.ng-invalid.ng-dirty { background-color: lightpink; }
input.ng-valid { background-color: lightgreen; }
span.error { color: red; font-weight: bold; }

4. Add span tag in each required field to show error

<span class="error" ng-show="custForm.fieldname.$error.required">This is a required field</span>

5. Add condition to show the error after writing in the field


6. Add code to show email error

<span class="error" ng-show="custForm.email.$dirty && custForm.email.$error.email">Email is invalid</span>

7. Add validation code for contact no field

8. Add ng-minlength and ng-maxlength attributes for contact no

9. Add span tag to show error

<span class="error" ng-show="custForm.contact.$dirty && custForm.contact.$error.minlength">Contact no can't be less than 11</span>
<span class="error" ng-show="custForm.contact.$dirty && custForm.contact.$error.maxlength">Contact no can't be more than 14</span>

Check the following video for more details.