Password Check

AngularJS directive that test if the passwords are equal.

by bruscopelliti

HTML

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
<!doctype html>
<html lang="en" ng-app="myApp">
    
    <head>
        <meta charset="utf-8" />
        <title>My AngularJS App</title>
    </head>
    
    <body ng-controller="stageController">
        <form name="myForm">
            <label for="pw1">Set a password:</label>
            <input type="password" id="pw1" name="pw1" ng-model="pw1" ng-required="" />
            <label for="pw2">Confirm the password:</label>
            <input type="password" id="pw2" name="pw2" ng-model="pw2" ng-required="" pw-check="pw1" />
            <div class="msg-block" ng-show="myForm.$error"> <span class="msg-error" ng-show="myForm.pw2.$error.pwmatch">Passwords don't match.</span> 
            </div>
        </form>
    </body>

</html>

CSS

* {
    margin:0;
    padding:0;
}
body {
    padding:10px;
}
label {
    display:block;
    font-size:14px;
    margin:10px 0 2px;
}
input {
    padding:1px 3px;
}
.msg-block {
    margin-top:5px;
}
.msg-error {
    color:#F00;
    font-size:14px;
}

JavaScript

'use strict';

// Declare app level module which depends on filters, and services
angular.module('myApp', ['myApp.directives']);

/* Controllers */
function stageController($scope) {
    $scope.pw1 = 'password';
}

/* Directives */
angular.module('myApp.directives', [])
    .directive('pwCheck', [function () {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, ctrl) {
            var firstPassword = '#' + attrs.pwCheck;
            elem.add(firstPassword).on('keyup', function () {
                scope.$apply(function () {
                    // console.info(elem.val() === $(firstPassword).val());
                    ctrl.$setValidity('pwmatch', elem.val() === $(firstPassword).val());
                });
            });
        }
    }
}]);