Validate two Fields Equality In AngularJS

  1. angular.module('app').directive('validateConfirmField', validateConfirmField);  
  2.   
  3. function validateConfirmField($parse)  
  4. {  
  5.     return {  
  6.         require: 'ngModel',  
  7.         link: function (scope, elem, attrs, ctrl)  
  8.         {  
  9.             scope.$watch(function ()  
  10.             {  
  11.                 if (!(ctrl.$modelValue) || !($parse(attrs.validateConfirmField)(scope)))  
  12.                 {  
  13.                     return true;  
  14.                 }  
  15.                 return ($parse(attrs.validateConfirmField)(scope)).toLowerCase() === ctrl.$modelValue.toLowerCase();  
  16.             }, function (currentValue)  
  17.             {  
  18.                 ctrl.$setValidity('validateConfirmField', currentValue);  
  19.             });  
  20.         }  
  21.     };  
  22. }  
  23. <!-- HTML View part where you want to validate your fields -->  
  24. < input type = "text"  
  25. name = "name1"  
  26. value = "Field1"  
  27. ng - model = "field1" > < input type = "text"  
  28. name = "name2"  
  29. value = "Field2"  
  30. ng - model = "field2"  
  31. data - validate - confirm - field = "field1" >  
  32.     <!-- HTML Validation -->  
  33.     < span ng - show = "form.name2.$error.validateConfirmField" > Field1 and Field2 does not match. < /span>