Input Matcher

This is a small demo for the input matcher. It showcases using it and displaying custom errors for the specific case where they do not match.

by Evan Sharp

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script src="https://rawgit.com/TheSharpieOne/angular-input-match/1.3.x/dist/angular-input-match.min.js"></script>
<!-- Scripts are in the Resouce panel -->
<div data-ng-app="myApp">
    <p>
        This is a very basic example/demo.<br />
        It will only fire after the confirm field has been modified (is no longer pristine)
    </p>
    <hr />
    <form name="myForm">
        Password: <input ng-model="user.password" type="password" name="password" data-ng-class="{'ng-invalid':myForm.confirmPassword.$error.match}" />
        Confirm: <input ng-model="user.passwordConfirm" type="password" data-match="user.password" name="confirmPassword" />
        <div data-ng-show="myForm.confirmPassword.$error.match">Passwords do not match!</div>
    </form>
    <hr />
    <p>Mis-match? {{myForm.confirmPassword.$error.match}}</p>
</div>

CSS

input{
    border:1px solid black;
    outline:none;
}
input.ng-invalid{
    border-color: red;
}

JavaScript

// Scripts are in the Resouce panel
'use strict';

angular.module('validation.match', []);

angular.module('validation.match').directive('match', match);

function match ($parse) {
    return {
        require: '?ngModel',
        restrict: 'A',
        link: function(scope, elem, attrs, ctrl) {
            if(!ctrl) {
                if(console && console.warn){
                    console.warn('Match validation requires ngModel to be on the element');
                }
                return;
            }
            
            var matchGetter = $parse(attrs.match);
            
            scope.$watch(getMatchValue, function(){
                ctrl.$validate();
            });
            
            ctrl.$validators.match = function(){
                return ctrl.$viewValue === getMatchValue();
            };

            function getMatchValue(){
                var match = matchGetter(scope);
                if(angular.isObject(match) && match.hasOwnProperty('$viewValue')){
                    match = match.$viewValue;
                }
                return match;
            }
        }
    };
}

angular.module('myApp',['validation.match'])