Form validation is a critical aspect of any web application to ensure data integrity and provide feedback to users. This article will walk you through the process of validating input and forms in AngularJS using a practical example of a member registration form.
Prerequisites
- Basic understanding of AngularJS
- Basic knowledge of HTML and CSS
Setting Up the Environment
First, ensure you have the necessary AngularJS library included in your project. You can download it from the official AngularJS website or include it via a CDN.
Example. Member Registration Form
We will use a member registration form to demonstrate how to validate inputs and the entire form in AngularJS.
HTML Structure
Here's the HTML structure for the member registration form. This form includes fields for House Number, Member Name, Mobile Number, and Member Email.
@model DempProject.UI.Models.EditModel
@{
Layout = "_AfterLoginLayout";
}
<section class="content-header">
<h1>
Member
</h1>
<ol class="breadcrumb">
<li><a href="/Member/index" tabindex="-1"><i class="fa fa-files-o"></i> Master</a></li>
<li class="active">Member</li>
</ol>
</section>
<section class="content">
<div class="row" ng-controller="MemberAddEditCtrl as ml" ng-init="ml.Inititlize('@Model.Id');" ng-cloak>
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">{{ml.HeadTitle}}</h3>
<div class="box-tools pull-right">
<a href="/Member/index" class="btn btn-sm btn-default btn-flat bg-yellow" tabindex="-1"><i class="fa fa-plus-square"></i> Back To List</a>
</div>
</div>
<form role="form" name="memberFrm" id="memberFrm" novalidate>
<div class="box-body">
<div class="form-group col-md-6" ng-class="{ 'has-error' : (memberFrm.HouseNo.$invalid && memberFrm.$submitted)}">
<label class="control-label" for="HouseNo">
<i class="fa fa-times-circle-o" ng-if="(memberFrm.HouseNo.$invalid && memberFrm.$submitted)"></i> House No. <span class="error-red">*</span>
</label>
<input type="text" class="form-control" id="HouseNo" name="HouseNo" placeholder="Enter House No." ng-model="ml.member.HouseNo" maxlength="50" autocomplete="off" ng-required="true">
@* <span class="help-block" ng-show="memberFrm.HouseNo.$error.required && memberFrm.$submitted">Please Enter House No</span>*@
</div>
<div class="form-group col-md-6">
<label class="control-label" for="MemberName">
Member Name
</label>
<input type="text" class="form-control" id="MemberName" name="MemberName" placeholder="Enter Member Name" ng-model="ml.member.MemberName" maxlength="50" autocomplete="off">
</div>
<div class="form-group col-md-6" >
<label class="control-label" for="MobileNo">
Mobile No.
</label>
<input type="text" class="form-control" id="MobileNo" name="MobileNo" placeholder="Enter Mobile No." ng-model="ml.member.MobileNo" maxlength="10" allow-only-number autocomplete="off">
</div>
<div class="form-group col-md-6" >
<label class="control-label" for="MemberEmail">
Member Email
</label>
<input type="text" class="form-control" id="MemberEmail" name="MemberEmail" placeholder="Enter Member Email" ng-model="ml.member.MemberEmail" maxlength="50" autocomplete="off">
</div>
</div>
<div class="box-footer">
<button type="submit" class="btn btn-success btn-sm" ng-click="memberFrm.$valid && ml.Save('SAVE&BACK')"><i class="fa fa-save"></i> {{ml.BtnTitle}} <i class="fa fa-arrow-circle-left"></i></button>
<button ng-if="!ml.isEdit" type="submit" class="btn btn-success btn-sm" ng-click="memberFrm.$valid && ml.Save('SAVE&NEW')"><i class="fa fa-save"></i> Save & Add New <i class="fa fa-plus-square"></i></button>
<a class="btn btn-danger btn-sm" href="/Member/index"><i class="fa fa-close"></i> Cancel</a>
</div>
</form>
<div class="overlay" ng-if="ml.IsRequesting">
<i class="fa fa-refresh fa-spin"></i>
</div>
</div>
</div>
</div>
</section>
<script src="~/MyApp/modules/Member/[email protected]"></script>
<script src="~/MyApp/modules/Member/[email protected]"></script>
AngularJS Controller
Now, let's create the AngularJS controller to handle the form initialization and validation logic. Save this as member_add_edit_ctrl.js
.
app.controller('MemberAddEditCtrl', ['$scope', 'MemberService', function($scope, MemberService) {
var vm = this;
vm.Inititlize = function(id) {
vm.member = {};
vm.HeadTitle = id ? 'Edit Member' : 'Add Member';
vm.BtnTitle = id ? 'Update' : 'Save';
if (id) {
MemberService.getMemberById(id).then(function(response) {
vm.member = response.data;
});
}
};
vm.Save = function(action) {
if ($scope.memberFrm.$valid) {
MemberService.saveMember(vm.member).then(function(response) {
if (response.data.success) {
if (action === 'SAVE&BACK') {
window.location.href = '/Member/index';
} else {
vm.member = {};
$scope.memberFrm.$setPristine();
}
}
});
}
};
}]);
AngularJS Service
Create a service to handle the HTTP requests related to member operations. Save this as member_srv.js
.
app.factory('MemberService', ['$http', function($http) {
return {
getMemberById: function(id) {
return $http.get('/api/member/' + id);
},
saveMember: function(member) {
return $http.post('/api/member', member);
}
};
}]);
Explanation
-
Form Structure: The form is structured with various input fields for House Number, Member Name, Mobile Number, and Member Email. Each input field is bound to a model in the AngularJS controller (ml.member
).
-
Validation
- The
ng-required
directive is used to ensure that the House Number is required.
- The
ng-class
directive adds the has-error
class if the House Number field is invalid and the form is submitted.
- Custom validation messages can be shown using AngularJS's validation directives, such as
ng-show
.
-
Controller Logic
- The
Inititlize
function initializes the form with existing member data if an ID is provided.
- The
Save
function handles form submission. It checks if the form is valid before sending the data to the server.
-
Service: The MemberService
provides methods to interact with the backend API for fetching and saving member data.
-
Overlay: The overlay with a spinner is shown when a request is in progress (ml.IsRequesting
).
Conclusion
Validating forms in AngularJS involves using built-in directives and AngularJS's robust validation mechanism. By structuring your form correctly and implementing the necessary validation logic in your controller and service, you can ensure that your form data is both accurate and reliable. This approach provides a solid foundation for handling form validation in any AngularJS application.