top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to do custom form validation in AngularJS?

0 votes
348 views
How to do custom form validation in AngularJS?
posted Nov 3, 2017 by Sathaybama

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

AngularJS allows you to create your own custom validation directives. For example, you have to compare
password and confirm password fields. To achieve thistask, you have to make a custom directive that will be fired
whenever the password or confirm password changes.
Creating custom directive to compare password and confirm password fields

//defining module
var myapp = angular.module('myapp', []);
//creating custom directive
myapp.directive('ngCompare', function () {
 return {
 require: 'ngModel',
 link: function (scope, currentEl, attrs, ctrl) {
 var comparefield = document.getElementsByName(attrs.ngCompare)[0]; //getting
first element
 compareEl = angular.element(comparefield);
 //current field key up
 currentEl.on('keyup', function () {
 if (compareEl.val() != "") {
 var isMatch = currentEl.val() === compareEl.val();
 ctrl.$setValidity('compare', isMatch);
scope.$digest();
 }
 });
 //Element to compare field key up
 compareEl.on('keyup', function () {
 if (currentEl.val() != "") {
 var isMatch = currentEl.val() === compareEl.val();
ctrl.$setValidity('compare', isMatch);
scope.$digest();
 }
 });
 }
 }
});

Using above created custom directive

<form name="userForm" ng-submit="submitForm()" novalidate>
 <!-- Password -->
 <div>
 <label>Password</label>
 <input type="Password" name="password" ng-required="true" ng-model="user.password">
 <p ng-show="userForm.password.$invalid">Your password is required.</p>
 </div>
 <!-- Confirm Password -->
 <div>
 <label>Confirm Password</label>
 <input type="Password" name="confirmPassword" ng-compare="password" ngrequired="true"
ng-model="user.confirmPassword" >
 <p ng-show="userForm.confirmPassword.$error.compare &&
!userForm.confirmPassword.$error.required">Confirm password doesn’t match.</p>
 </div>
 <!-- Other code has been removed for clarity-->
</form>
answer Nov 3, 2017 by Shivaranjini
...