AngularJS:添加检查密码输入是否一致的功能

感谢作者(http://blog.brunoscopelliti.com/angularjs-directive-to-check-that-passwords-match)

利用AngularJS的directive,我们可以很方便的实现检验功能。代码如下:

 1 // 密码验证directive
 2 ftitAppModule.directive('pwCheck', [function () {
 3     return {
 4         require: 'ngModel',
 5         link: function (scope, elem, attrs, ctrl) {
 6             var firstPassword = '#' + attrs.pwCheck;
 7             elem.add(firstPassword).on('keyup', function () {
 8                 scope.$apply(function () {
 9                     var v = elem.val()===$(firstPassword).val();
10                     ctrl.$setValidity('pwmatch', v);
11                 });
12             });
13         }
14     }
15 }]);

Demo html代码(feedback部分请参考http://www.cnblogs.com/ilovewindy/p/3795993.html):

 1 <div class="form-group">
 2     <label for="userPassword">密码</label>
 3     <input type="password" class="form-control" id="userPassword" name="userPassword"
 4            placeholder="请输入密码" ng-model="selectedUser.userPassword">
 5 </div>
 6 <div class="form-group has-feedback"
 7      ng-class="{'has-success' : !usrMgrForm.confirmPassword.$pristine && usrMgrForm.confirmPassword.$valid,
 8                 'has-error' : !usrMgrForm.confirmPassword.$pristine && usrMgrForm.confirmPassword.$invalid }">
 9     <label for="confirmPassword">确认密码</label>
10     <input type="password" class="form-control" id="confirmPassword" name="confirmPassword"
11            placeholder="请再次输入密码" ng-model="selectedUser.confirmPassword" pw-check="userPassword">
12     <div ng-show="!usrMgrForm.confirmPassword.$pristine && tagName.confirmPassword.$valid">
13         <span class="glyphicon glyphicon-ok form-control-feedback"></span>
14     </div>
15     <div ng-show="!usrMgrForm.confirmPassword.$pristine && usrMgrForm.confirmPassword.$invalid">
16         <span class="glyphicon glyphicon-remove form-control-feedback"></span>
17     </div>
18 </div>

效果如下:

posted @ 2014-08-20 11:26  GreatK  阅读(3404)  评论(0编辑  收藏  举报