angularjs 表单自定义验证指令
密码一致性验证
Demo1:在第一个密码框添加Id 属性,通过Id 获取其value 值,并与第二个密码框的value 值做实时对比
Demo2:通过第二个密码框的scope 拿到传入第一个密码框的值,并实时比较两个密码框的值
html 代码:
<div class="form-group"> <label class="control-label" for="password">密码</label> <input id="password" class="form-control" name="password" ng-model="password" type="password" required /> <div ng-show="userForm.$submitted && userForm.password.$error.required" class="help-block">请输入密码</div> </div> <div class="form-group"> <label class="control-label" for="checkPassword">确认密码</label> <input equal-to="password" class="form-control" name="checkPassword" ng-model="checkPassword" type="password" required /> <div ng-show="userForm.$submitted && userForm.checkPassword.$error.required" class="help-block">请再次输入密码</div> <div ng-show="userForm.$submitted && userForm.checkPassword.$error.pwmatch" class="help-block">两次密码输入不一致</div> </div>
js 代码:
angular.module('user-groups').directive('equalTo',[function(){ return { require: 'ngModel', link: function(scope,elem,attrs,ctrl){ //第一个密码输入框的Id var password = '#' + attrs.equalTo; //第一个密码输入框绑定事件 $(elem).add(password).on('keyup', function () { scope.$apply(function () { var result = elem.val()===$(password).val(); //设置验证是否通过 ctrl.$setValidity('pwmatch',result); }); }); } }; }]); //此方法直接提交,scope.password=undefined,elem.val()=''; angular.module('user-groups').directive('equalTo', function () { return{ require: 'ngModel', scope: { password:'=equalTo' }, link: function(scope,elem,attrs,ctrl){ scope.$watch('password', function(){ ctrl.$setValidity('pwmatch',elem.val()===scope.password); }); elem.on('keyup', function(){ scope.$apply(function(){ ctrl.$setValidity('pwmatch',elem.val()===scope.password); }); }); } } })
未完待续 ...