使用 Angular 指令在一个或其他字段模型更改(每次击键)时验证密码和确认密码字段 [英] Validating Password And Confirm Password Fields Whenever One Or The Other Fields Model Changes (Each Keystroke) With Angular Directive

查看:26
本文介绍了使用 Angular 指令在一个或其他字段模型更改(每次击键)时验证密码和确认密码字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个 Angular 指令,用于验证密码并确认密码字段匹配.它在某种程度上起作用,当密码不匹配时它确实会引发错误.但是,在您在两个字段中都输入数据之前,它不会引发错误.我如何才能在您在一个或另一个字段中输入数据时立即抛出密码不匹配的错误?

这是指令(必须将其添加到需要匹配的两个字段中):

.directive('passwordVerify', function() {返回 {限制: 'A',//只在元素属性上激活require: '?ngModel',//获取 NgModelController链接:功能(范围,元素,属性,ngModel){//如果(!ngModel)返回;//如果没有 ng-model 则什么都不做//观察自己的值并在变化时重新验证scope.$watch(attrs.ngModel, function() {证实();});//观察另一个值并在更改时重新验证attrs.$observe('passwordVerify', function(val) {证实();});var 验证 = 函数(){//值var val1 = ngModel.$viewValue;var val2 = attrs.passwordVerify;//设置有效性ngModel.$setValidity('passwordVerify', !val1 || !val2 || val1 === val2);};}};});

这是我表单中的指令:

<div class="small-12 列"><标签>密码<输入ng-class="{ notvalid: 提交 && add_user_form.user_password.$invalid }"类=教师输入"id="用户密码"类型=密码"名称='用户_密码'占位符=密码"值=''必需的ng-model="user.user_password"密码验证="[[user.confirm_password]]"><p class="help-text"><span class=" ">必需</span></p>

<div class="small-12 列"><标签>确认密码<输入ng-class="{ 无效:已提交 && add_user_form.confirm_password.$invalid }"类=教师输入"id="confirm_password"ng-model="user.confirm_password"名称=确认密码"类型=密码"占位符=确认密码"名称=用户确认密码"必需的密码验证="[[user.user_password]]"><p class="help-text"><span class="">输入匹配的密码</span></p>

解决方案

只需更改最后一个检查:

ngModel.$setValidity('passwordVerify', !val1 || !val2 || val1 === val2);

到:

ngModel.$setValidity('passwordVerify', val1 === val2);

这是一个工作版本:

(function() {严格使用";有角的.module('app', ['ngMessages']).controller('mainCtrl', mainCtrl).directive('passwordVerify', passwordVerify);函数 mainCtrl($scope) {//一些代码}函数密码验证(){返回 {限制: 'A',//只在元素属性上激活require: '?ngModel',//获取 NgModelController链接:功能(范围,元素,属性,ngModel){如果(!ngModel)返回;//如果没有 ng-model 则什么都不做//观察自己的值并在变化时重新验证scope.$watch(attrs.ngModel, function() {证实();});//观察另一个值并在更改时重新验证attrs.$observe('passwordVerify', function(val) {证实();});var 验证 = 函数(){//值var val1 = ngModel.$viewValue;var val2 = attrs.passwordVerify;//设置有效性ngModel.$setValidity('passwordVerify', val1 === val2);};}}}})();

<头><script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css"/><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.5.7/angular-messages.min.js"></script><body ng-controller="mainCtrl"><表单名称="add_user_form"><div class="col-md-12"><div class="form-group" ng-class="{ 'has-error' : add_user_form.user_password.$dirty && add_user_form.user_password.$invalid }"><p class="help-text">输入密码</p><input type="password" class="form-control" id="user_password" name="user_password" placeholder="password" required ng-model="user.user_password" password-verify="{{user.confirm_password"}}"><div class="help-block" ng-messages="add_user_form.user_password.$error" ng-if="add_user_form.user_password.$dirty"><p ng-message="required">这个字段是必填的</p><p ng-message="minlength">这个字段太短了</p><p ng-message="maxlength">这个字段太长</p><p ng-message="required">这个字段是必填的</p><p ng-message="passwordVerify">不匹配!</p>

<div class="form-group" ng-class="{ 'has-error' : add_user_form.confirm_password.$dirty && add_user_form.confirm_password.$invalid }"><p class="help-text">输入匹配的密码</p><input class="form-control" id="confirm_password" ng-model="user.confirm_password" name="confirm_password" type="password" placeholder="confirm password" required password-verify="{{user.用户密码}}"><div class="help-block" ng-messages="add_user_form.confirm_password.$error" ng-if="add_user_form.confirm_password.$dirty"><p ng-message="required">这个字段是必填的</p><p ng-message="minlength">这个字段太短了</p><p ng-message="maxlength">这个字段太长</p><p ng-message="required">这个字段是必填的</p><p ng-message="passwordVerify">不匹配!</p>

</表单></html>

希望能帮到你.

I currently have an Angular Directive that validates a password and confirm password field as matching. It works to a point, it does throw an error when the passwords do not match. However, it doesn't throw the error until you have entered data in both fields. How can I make it so the error for mismatched passwords is thrown as soon as you enter data in one field or the other?

Here is the directive (it has to be added to both fields that need to match):

.directive('passwordVerify', function() {
   return {
      restrict: 'A', // only activate on element attribute
      require: '?ngModel', // get a hold of NgModelController
      link: function(scope, elem, attrs, ngModel) {
         //if (!ngModel) return; // do nothing if no ng-model

         // watch own value and re-validate on change
         scope.$watch(attrs.ngModel, function() {
            validate();
         });

         // observe the other value and re-validate on change
         attrs.$observe('passwordVerify', function(val) {
            validate();
         });

         var validate = function() {
            // values
            var val1 = ngModel.$viewValue;
            var val2 = attrs.passwordVerify;

           // set validity
           ngModel.$setValidity('passwordVerify', !val1 || !val2 || val1 === val2);
        };
      }
   };
});

And here is the directive in my form:

<div class="small-5 columns">
    <div class="small-12 columns">
        <label>
            Password
            <input 
                ng-class="{ notvalid: submitted && add_user_form.user_password.$invalid }" 
                class="instructor-input" 
                id="user_password" 
                type="password" 
                name='user_password' 
                placeholder="password" 
                value='' 
                required 
                ng-model="user.user_password" 
                password-verify="[[user.confirm_password]]"
            >
        </label>
        <p class="help-text">
            <span class="   ">Required</span>
        </p>
        <div 
            class="help-block" 
            ng-messages="add_user_form.user_password.$error" 
            ng-show="add_user_form.user_password.$touched || add_user_form.user_password.$dirty"
        >
        <span class="red">
            <div ng-messages-include="/app/views/messages.html" ></div>
        </span>
    </div>
</div>
<div class="small-12 columns">
    <label>
        Confirm Password
        <input 
            ng-class="{ notvalid: submitted && add_user_form.confirm_password.$invalid }" 
            class="instructor-input" 
            id="confirm_password" 
            ng-model="user.confirm_password" 
            name="confirm_password" 
            type="password" 
            placeholder="confirm password" 
            name="user_confirm_passsword" 
            required 
            password-verify="[[user.user_password]]"
        >
    </label>
    <p class="help-text">
        <span class="   ">
            Enter matching password
        </span>
    </p>
    <div 
        class="help-block" 
        ng-messages="add_user_form.confirm_password.$error" 
        ng-show="add_user_form.confirm_password.$dirty || add_user_form.confirm_password.$touched "
    >
        <span class="red">
            <div 
                ng-messages-include="/app/views/messages.html"
            ></div>
        </span>
    </div>
</div>

解决方案

Just change the last check:

ngModel.$setValidity('passwordVerify', !val1 || !val2 || val1 === val2);

to:

ngModel.$setValidity('passwordVerify', val1 === val2);

Here's a working version:

(function() {
  "use strict";
  angular
    .module('app', ['ngMessages'])
    .controller('mainCtrl', mainCtrl)
    .directive('passwordVerify', passwordVerify);

  function mainCtrl($scope) {
    // Some code
  }

  function passwordVerify() {
    return {
      restrict: 'A', // only activate on element attribute
      require: '?ngModel', // get a hold of NgModelController
      link: function(scope, elem, attrs, ngModel) {
        if (!ngModel) return; // do nothing if no ng-model

        // watch own value and re-validate on change
        scope.$watch(attrs.ngModel, function() {
          validate();
        });

        // observe the other value and re-validate on change
        attrs.$observe('passwordVerify', function(val) {
          validate();
        });

        var validate = function() {
          // values
          var val1 = ngModel.$viewValue;
          var val2 = attrs.passwordVerify;

          // set validity
          ngModel.$setValidity('passwordVerify', val1 === val2);
        };
      }
    }
  }
})();

<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-messages/1.5.7/angular-messages.min.js"></script>
</head>

<body ng-controller="mainCtrl">
  <form name="add_user_form">
    <div class="col-md-12">
      <div class="form-group" ng-class="{ 'has-error' : add_user_form.user_password.$dirty && add_user_form.user_password.$invalid }">
        <p class="help-text">Enter password</p>
        <input type="password" class="form-control" id="user_password" name="user_password" placeholder="password" required ng-model="user.user_password" password-verify="{{user.confirm_password}}">
        <div class="help-block" ng-messages="add_user_form.user_password.$error" ng-if="add_user_form.user_password.$dirty">
          <p ng-message="required">This field is required</p>
          <p ng-message="minlength">This field is too short</p>
          <p ng-message="maxlength">This field is too long</p>
          <p ng-message="required">This field is required</p>
          <p ng-message="passwordVerify">No match!</p>
        </div>
      </div>
      <div class="form-group" ng-class="{ 'has-error' : add_user_form.confirm_password.$dirty && add_user_form.confirm_password.$invalid }">
        <p class="help-text">Enter matching password</p>
        <input class="form-control" id="confirm_password" ng-model="user.confirm_password" name="confirm_password" type="password" placeholder="confirm password" required password-verify="{{user.user_password}}">
        <div class="help-block" ng-messages="add_user_form.confirm_password.$error" ng-if="add_user_form.confirm_password.$dirty">
          <p ng-message="required">This field is required</p>
          <p ng-message="minlength">This field is too short</p>
          <p ng-message="maxlength">This field is too long</p>
          <p ng-message="required">This field is required</p>
          <p ng-message="passwordVerify">No match!</p>
        </div>
      </div>
    </div>
  </form>
</body>

</html>

I hope it helps.

这篇关于使用 Angular 指令在一个或其他字段模型更改(每次击键)时验证密码和确认密码字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆