programing

angularjs에서의 패스워드 검사 지시어

oldcodes 2023. 3. 10. 22:45
반응형

angularjs에서의 패스워드 검사 지시어

비밀번호 확인 지시문을 작성 중입니다.

 Directives.directive("passwordVerify",function(){
    return {
        require:"ngModel",
        link: function(scope,element,attrs,ctrl){
            ctrl.$parsers.unshift(function(viewValue){
                var origin = scope.$eval(attrs["passwordVerify"]);
                if(origin!==viewValue){
                    ctrl.$setValidity("passwordVerify",false);
                    return undefined;
                }else{
                    ctrl.$setValidity("passwordVerify",true);
                    return viewValue;
                }
            });

        }
    };
});

html:

<input data-ng-model='user.password' type="password" name='password' placeholder='password' required>
<input data-ng-model='user.password_verify' type="password" name='confirm_password' placeholder='confirm password' required data-password-verify="user.password">

형식의 2개의 패스워드 필드를 지정하면 양쪽 패스워드 값이 같을 경우 디렉티브의 영향을 받는 필드가 유효합니다.이 문제는 단방향(즉, password-verify 필드에 비밀번호를 입력할 때)으로 동작한다는 것입니다.단, 원래 비밀번호 필드가 갱신되면 비밀번호 확인은 유효하지 않습니다.

어떻게 '양방향 바인딩 검증'을 할 수 있는지 아세요?

값 1과 값 2 중 어느 쪽이 변경되었는지에 관계없이 양쪽 입력 필드를 다시 검증하기 위해 다음 지시문을 사용합니다.

지시:

'use strict';

angular.module('myApp').directive('equals', 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('equals', function (val) {
        validate();
      });

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

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

사용.

<input type="password" ng-model="value1" equals="{{value2}}" required>
<input type="password" ng-model="value2" equals="{{value1}}" required>

이를 위해 별도의 지시문을 작성할 필요가 없습니다.Angular UI 암호 유효성 검사 도구가 이미 있습니다.이를 통해 다음 작업을 수행할 수 있습니다.

<input name="password" required ng-model="password">
<input name="confirm_password"
       ui-validate=" '$value==password' "
       ui-validate-watch=" 'password' ">

 Passwords match? {{!!form.confirm_password.$error.validator}}

이것으로 해결할 수 있습니다.

표시:

<div ng-controller='Ctrl'>
   <form name='form'>
      <input data-ng-model='user.password' type="password" name='password' placeholder='password' required>
      <div ng-show="form.password.$error.required">
        Field required</div>
      <input ng-model='user.password_verify' type="password" name='confirm_password' placeholder='confirm password' required data-password-verify="user.password">
      <div ng-show="form.confirm_password.$error.required">
        Field required!</div>
      <div ng-show="form.confirm_password.$error.passwordVerify">
        Fields are not equal!</div>
   </form
</div>

지시.

var app = angular.module('myApp', []);

app.directive("passwordVerify", function() {
   return {
      require: "ngModel",
      scope: {
        passwordVerify: '='
      },
      link: function(scope, element, attrs, ctrl) {
        scope.$watch(function() {
            var combined;

            if (scope.passwordVerify || ctrl.$viewValue) {
               combined = scope.passwordVerify + '_' + ctrl.$viewValue; 
            }                    
            return combined;
        }, function(value) {
            if (value) {
                ctrl.$parsers.unshift(function(viewValue) {
                    var origin = scope.passwordVerify;
                    if (origin !== viewValue) {
                        ctrl.$setValidity("passwordVerify", false);
                        return undefined;
                    } else {
                        ctrl.$setValidity("passwordVerify", true);
                        return viewValue;
                    }
                });
            }
        });
     }
   };
});

이에 대한 또 다른 관점은 한 입력의 모델을 다른 입력의 값에 맞추는 것입니다.

app.directive('nxEqual', function() {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, model) {
            if (!attrs.nxEqual) {
                console.error('nxEqual expects a model as an argument!');
                return;
            }
            scope.$watch(attrs.nxEqual, function (value) {
                model.$setValidity('nxEqual', value === model.$viewValue);
            });
            model.$parsers.push(function (value) {
                var isValid = value === scope.$eval(attrs.nxEqual);
                model.$setValidity('nxEqual', isValid);
                return isValid ? value : undefined;
            });
        }
    };
});

박스의 이 「 「 」인 경우login.password과 같은 합니다.nx-equal="login.password"에 대해 설명합니다formName.elemName.$error.nxEqual ★★★★★★★★★★★★★★★★★★.

<form name="form">
    <input type="password" ng-model="login.password">
    <input type="password" ng-model="login.verify" nx-equal="login.password" name="verify">
    <span ng-show="form.verify.$error.nxEqual">Must be equal!</span>
</form>

확장 버전:

하여 「이것만 안 되었습니다.nxEqual검증 입력에 값이 있는 경우에만 오류가 발생합니다. 이외의 경우는, 「」를 참조해 주세요.nxEqual을 사용하다확장 버전은 다음과 같습니다.

app.directive('nxEqualEx', function() {
    return {
        require: 'ngModel',
        link: function (scope, elem, attrs, model) {
            if (!attrs.nxEqualEx) {
                console.error('nxEqualEx expects a model as an argument!');
                return;
            }
            scope.$watch(attrs.nxEqualEx, function (value) {
                // Only compare values if the second ctrl has a value.
                if (model.$viewValue !== undefined && model.$viewValue !== '') {
                    model.$setValidity('nxEqualEx', value === model.$viewValue);
                }
            });
            model.$parsers.push(function (value) {
                // Mute the nxEqual error if the second ctrl is empty.
                if (value === undefined || value === '') {
                    model.$setValidity('nxEqualEx', true);
                    return value;
                }
                var isValid = value === scope.$eval(attrs.nxEqualEx);
                model.$setValidity('nxEqualEx', isValid);
                return isValid ? value : undefined;
            });
        }
    };
});

이렇게 사용할 수 있습니다.

<form name="form">
    <input type="password" ng-model="login.password">
    <input type="password" ng-model="login.verify" nx-equal-ex="login.password" name="verify">
    <span ng-show="form.verify.$error.nxEqualEx">Must be equal!</span>
</form>

체험: http://jsfiddle.net/gUSZS/

나는 지시 없이 그것을 해 왔다.

<input type="password" ng-model="user.password" name="uPassword" required placeholder='Password' ng-minlength="3" ng-maxlength="15" title="3 to 15 characters" />
    <span class="error" ng-show="form.uPassword.$dirty && form.uPassword.$error.minlength">Too short</span>
    <span ng-show="form.uPassword.$dirty && form.uPassword.$error.required">Password required.</span><br />

    <input type="password" ng-model="user.confirmpassword" name="ucPassword" required placeholder='Confirm Password' ng-minlength="3" ng-maxlength="15" title="3 to 15 characters" />
    <span class="error" ng-show="form.ucPassword.$dirty && form.ucPassword.$error.minlength">Too short</span>
    <span ng-show="form.ucPassword.$dirty && form.ucPassword.$error.required">Retype password.</span>
    <div ng-show="(form.uPassword.$dirty && form.ucPassword.$dirty) && (user.password != user.confirmpassword)">
        <span>Password mismatched</span>
    </div>

https://github.com/wongatech/angular-confirm-field은 이를 위한 좋은 프로젝트입니다.

예: http://wongatech.github.io/angular-confirm-field/

아래 코드는 구현된 기능을 가진 2개의 입력 필드를 보여줍니다.

<input ng-confirm-field ng-model="emailconfirm" confirm-against="email" name="my-email-confirm"/>
<input ng-model="email" name="my-email" />

각도 1.3.0~120012에서는 비활성 입력이 ngModel에 기록되지 않기 때문에 여기서 볼 수 있듯이 시청 후 검증할 수 없습니다.http://plnkr.co/edit/W6AFHF308nyKVMQ9vomw?p=preview새로운 검증자 파이프라인이 도입되었습니다.이 파이프라인에 접속하면 동일한 작업을 수행할 수 있습니다.

실제로 일반적인 추가 검증자를 위한 바우어 컴포넌트를 만들었습니다.이 컴포넌트는 https://github.com/intellix/angular-validators 입니다.이 컴포넌트에는 이 컴포함되어 있습니다.

angular.module('validators').directive('equals', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, elem, attrs, ngModel)
        {
            if (!ngModel) return;

            attrs.$observe('equals', function() {
                ngModel.$validate();
            });

            ngModel.$validators.equals = function(value) {
                return value === attrs.equals;
            };
        }
    };
});

angular.module('validators').directive('notEquals', function() {
    return {
        restrict: 'A',
        require: '?ngModel',
        link: function(scope, elem, attrs, ngModel)
        {
            if (!ngModel) return;

            attrs.$observe('notEquals', function() {
                ngModel.$validate();
            });

            ngModel.$validators.notEquals = function(value) {
                return value === attrs.notEquals;
            };
        }
    };
});

이 지령을 사용한 적이 있습니다.

 .directive('sameAs', function() {
  return {
    require: 'ngModel',
    link: function(scope, elm, attrs, ctrl) {
      ctrl.$parsers.unshift(function(viewValue) {
        if (viewValue === scope[attrs.sameAs]) {
          ctrl.$setValidity('sameAs', true);
          return viewValue;
        } else {
          ctrl.$setValidity('sameAs', false);
          return undefined;
        }
      });
    }
  };
});

사용.

     <input ... name="password" />
    <input type="password" placeholder="Confirm Password" 
name="password2" ng-model="password2" ng-minlength="9" same-as='password' required>

나는 같은 문제를 다루다가 Piotr Buda가 쓴 좋은 블로그 글을 발견했다.그것은 좋은 읽을거리이고 그 과정을 잘 설명해준다.코드는 다음과 같습니다.

directives.directive("repeatPassword", function() {
    return {
        require: "ngModel",
        link: function(scope, elem, attrs, ctrl) {
            var otherInput = elem.inheritedData("$formController")[attrs.repeatPassword];

            ctrl.$parsers.push(function(value) {
                if(value === otherInput.$viewValue) {
                    ctrl.$setValidity("repeat", true);
                    return value;
                }
                ctrl.$setValidity("repeat", false);
            });

            otherInput.$parsers.push(function(value) {
                ctrl.$setValidity("repeat", value === ctrl.$viewValue);
                return value;
            });
        }
    };
});

따라서 다음과 같은 작업을 수행할 수 있습니다.

<input type="password" name="repeatPassword" id="repeatPassword" placeholder="repeat password" ng-model="user.repeatPassword" repeat-password="password" required>

저자의 공로가 되다

이것만으로는 불충분합니까?

<input type="password" ng-model="passwd1" />
<input type="password" ng-model="passwd2" />
<label ng-show="passwd1 != passwd2">Passwords do not match...</label>
<button ng-disabled="passwd1 != passwd2">Save</button>

단순하고, 나한테는 딱 맞아.

이 솔루션은 Dominic Watson이 준 솔루션과 유사하며 $validator를 사용하고 있으며 제가 가장 좋아하는 솔루션입니다.유일하게 변경된 것은 표현식을 볼 수 있다는 것입니다.

$validators 모델 값이 변경될 때마다 적용되는 검증자 모음입니다.개체 내의 키 값은 검증자의 이름을 참조하고 함수는 검증 작업을 참조합니다.유효성 검사 작업은 모델 값과 함께 인수로 제공되며 해당 유효성 검사 응답에 따라 참 또는 거짓 값을 반환해야 합니다.

https://code.angularjs.org/1.3.15/docs/api/ng/type/ngModel.NgModelController 에서

각도 1.3을 쓰고 있어요.제 지시는 이렇게 생겼습니다.

angular.module('app').directive("passwordConfirm", function() {
    "use strict";
    return {
        require : "ngModel",
        restrict : "A",
        scope : {
            //We will be checking that our input is equals to this expression
            passwordConfirm : '&'
        },
        link : function(scope, element, attrs, ctrl) {
            //The actual validation
            function passwordConfirmValidator(modelValue, viewValue) {
                return modelValue == scope.passwordConfirm();
            }
            //Register the validaton when this input changes
            ctrl.$validators.passwordConfirm = passwordConfirmValidator;
            //Also validate when the expression changes
            scope.$watch(scope.passwordConfirm, ctrl.$validate);
        }
    };
});

사용하기 위해서

<input type="password" ng-model="user.password"/>
<input type="password" ng-model="user.confirmPassword" 
                password-confirm="user.password" />

두 개의 입력 필드를 가진 폼을 검증하기 위해, 나는 가장 적합한 방법을 찾는다.

지시.

app.directive('passwordVerify', function() {
return {
    require: 'ngModel',
    link: function (scope, elem, attrs, ctrl) {
        if (!attrs.passwordVerify) {
            return;
        }
        scope.$watch(attrs.passwordVerify, function (value) {
          if( value === ctrl.$viewValue && value !== undefined) {
             ctrl.$setValidity('passwordVerify', true);
             ctrl.$setValidity("parse",undefined);
          }
          else {
             ctrl.$setValidity('passwordVerify', false);
          }
        });
        ctrl.$parsers.push(function (value) {
            var isValid = value === scope.$eval(attrs.passwordVerify);
            ctrl.$setValidity('passwordVerify', isValid);
            return isValid ? value : undefined;
        });
    }
  };
});

HTML

     <div class="row">
        <div class="col-md-10 col-md-offset-1">
          <div class="form-group" ng-class="{ 'has-error': form.password.$dirty && form.password.$error.required || (form.password.$error.minlength || form.password.$error.maxlength)}">
              <input type="password" name="password" ng-minlength="6" ng-maxlength="16" id="password" class="form-control" placeholder="Password" ng-model="user.password" required />
              <span ng-show="form.password.$dirty && form.password.$error.required" class="help-block">Password is required</span>
              <span ng-show="form.password.$error.minlength || form.password.$error.maxlength" class="help-block">Password must be 6-16 character long</span>
          </div>
        </div>
       </div>
       <div class="row">
         <div class="col-md-10 col-md-offset-1">
           <div class="form-group" ng-class="{ 'has-error': (form.confirm_password.$dirty && form.confirm_password.$error.required) || form.confirm_password.$error.passwordVerify }">
              <input type="password" name="confirm_password" id="confirm_password" class="form-control" placeholder="Confirm Password" ng-model="user.confirm_password" required password-verify="user.password" />
              <span ng-show="form.confirm_password.$dirty && form.confirm_password.$error.required" class="help-block">Confirm Password is required</span>
              <span ng-show="form.confirm_password.$error.passwordVerify" class="help-block">Please make sure passwords match & must be 6-16 character long</span>
          </div>
        </div>
      </div>

이 방법은 양방향으로 작동하며 단순하고 깨끗합니다.

자바스크립트

var app = angular.module("app");

app.controller("SamePaswordController", function () {

  this.password;
  this.confirm;

  this.save = function () {
    alert("Saved!");
  };
}


app.directive("match", function () {
  return {
    restrict:"A",
    require:"ngModel",

    link: function(scope, element, attrs, ctrl) {

      function matchValidator(value) {      

        scope.$watch(attrs.match, function(newValue, oldValue) {

          var isValid = value === scope.$eval(attrs.match);                    
          ctrl.$setValidity('match', isValid);

        });

        return value;
      }

      ctrl.$parsers.push(matchValidator);
    }
  };
});

HTML: match 디렉티브를 메모합니다.

<form name="regForm" ng-controller="SamePaswordController as regCtrl"
      ng-submit="regForm.$valid && regCtrl.save()" novalidate>

  <input name="password" ng-model="regCtrl.password" 
         type="password" required placeholder="Password"/>                

  <input name="confirm" ng-model="regCtrl.confirm" match="regCtrl.password"
         type="password" required placeholder="Confirm password"/>


  <div> regForm is valid:{{regForm.$valid}}</div>

  <input type="submit" value="Save"/>

</form>

이 예에서는 https://github.com/rogithub/roangularjs 를 사용하여 repo 를 복제할 수 있습니다.

지시적인 솔루션은 아니지만 나에게 효과가 있습니다.

<input ng-model='user.password'
 type="password"
 name='password'
 placeholder='password'
 required>
<input ng-model='user.password_verify'
 type="password" 
 name='confirm_password'
 placeholder='confirm password'
 ng-pattern="getPattern()"
 required>

컨트롤러 내:

//Escape the special chars
    $scope.getPattern = function(){
        return $scope.user.password && 
              $scope.user.password.replace(/([.*+?^${}()|\[\]\/\\])/g, '\\$1');
    }

http://plnkr.co/edit/QDTnipCsHdg56vgygsqC?p=preview

다음은 그 문제에 대한 저의 견해입니다.이 디렉티브는 스코프가 아닌 폼 값과 비교됩니다.

'use strict';
(function () {
    angular.module('....').directive('equals', function ($timeout) {
        return {
            restrict: 'A',
            require: ['^form', 'ngModel'],
            scope: false,
            link: function ($scope, elem, attrs, controllers) {
                var validationKey = 'equals';
                var form = controllers[0];
                var ngModel = controllers[1];

                if (!ngModel) {
                    return;
                }

                //run after view has rendered
                $timeout(function(){
                    $scope.$watch(attrs.ngModel, validate);

                    $scope.$watch(form[attrs.equals], validate);
                }, 0);

                var validate = function () {
                    var value1 = ngModel.$viewValue;
                    var value2 = form[attrs.equals].$viewValue;
                    var validity = !value1 || !value2 || value1 === value2;
                    ngModel.$setValidity(validationKey, validity);
                    form[attrs.equals].$setValidity(validationKey,validity);
                };
            }
        };
    });
})();

이제 HTML에서는 스코프 값이 아닌 실제 형식을 참조합니다.

<form name="myForm">
  <input type="text" name="value1" equals="value2">
  <input type="text" name="value2" equals="value1">
  <div ng-show="myForm.$invalid">The form is invalid!</div>
</form>

양쪽 입력이 변경되었을 때 유효성을 확인하기 위해 다음 코드(다른 모든 답변의 조합)를 사용합니다.

angular.module('app.directives')
.directive('passwordVerify', [function () {
    return {
        require: '?ngModel',
        restrict: 'A',
        scope: {
            origin: '=passwordVerify'
        },
        link: function (scope, element, attrs, ctrl) {
            if(!ctrl) {
                return;
            }

            function validate(value) {
                ctrl.$setValidity('passwordMatch', scope.origin === value);
                return value;
            }

            ctrl.$parsers.unshift(validate);

            scope.$watch('origin', function(value) {
                validate(ctrl.$viewValue);
            });
        }
    };
}]);

우선, 이 훌륭한 사례를 게재해 주신 프레드릭에게 감사드립니다.우연히 알게 된 작은 문제가 하나 있다.http://jsfiddle.net/gUSZS/에 게시한 바이올린에 대해

암호를 입력하고 확인 입력 요소에 동일한 암호를 입력하면 모든 것이 정상적으로 작동하지만 두 번째 상자에 공백을 추가하면 각도가 자동으로 해당 공간을 잘라냅니다.즉, 디렉티브는 여분의 공간을 "확인"하지 않습니다.현재 비밀번호는 다르지만 형식은 여전히 유효합니다.

이 문제를 해결하려면

ng-trim="false"

입력 요소로 이동합니다.이것은 각도 1.0.3에서는 동작하지 않기 때문에, 이 바이올린으로 시험해 보고 싶은 경우는, 1.1.1을 바이올린에 추가할 필요가 있습니다(http://ajax.googleapis.com/ajax/libs/angularjs/1.1.1/angular.js)

하지만 Thanx Frederic씨, 저는 당신의 솔루션을 제 앱에서 사용할 것입니다!

안톤 추신Frederic의 투고에 대해 코멘트를 하고 싶었지만, 저는 이 포럼에 처음 와서 충분한 신용이 없는 것 같습니다.제 코멘트가 마음에 드시면 투표해주시면 감사하겠습니다:-)

별도의 지시는 필요 없습니다. 이에 대한 저의 견해는 다음과 같습니다.

HTML:

<div class="form-group" data-ng-class="{ 'has-error': submitted && !form.new_passwd.$valid }">
    <input type="password" name="new_passwd" class="form-control" data-ng-model="data.new_passwd" placeholder="New Password" required data-ng-pattern="passwdRegex">
    <small class="help-block" data-ng-show="submitted && form.new_passwd.$error.required">New password is required!</small>
    <small class="help-block" data-ng-show="submitted && !form.new_passwd.$error.required && form.new_passwd.$error.pattern">New password is not strong enough!</small>
</div>

<div class="form-group" data-ng-class="{ 'has-error': submitted && !form.new_passwd_conf.$valid }">
    <input type="password" name="new_passwd_conf" class="form-control" data-ng-model="data.new_passwd_conf" placeholder="Confirm New Password" required data-ng-pattern="passwdConfRegex">
    <small class="help-block" data-ng-show="submitted && form.new_passwd_conf.$error.required">New password confirmation is required!</small>
    <small class="help-block" data-ng-show="submitted && !form.new_passwd_conf.$error.required && form.new_passwd_conf.$error.pattern">New password confirmation does not match!</small>
</div>

Javascript:

$scope.passwdRegex = /^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[^\da-zA-Z]).{8,}$/;
$scope.$watch('data.new_passwd', function() {
    $scope.passwdConfRegex = new RegExp(Regex.escape($scope.data.new_passwd));
});

Regex.escape()는 여기서 찾을 수 있습니다.

마법처럼 작동!

기존 솔루션을 많이 추가할 경우 이 방법이 효과적입니다.

(Jan Laussmann의 답변은 최신 Angular와 함께 작동하지 않습니다.JS 베타 릴리즈).

지시:

angular.module('myApp').directive('matchValidator', [function() {
        return {
            require: 'ngModel',
            link: function(scope, elm, attr, ctrl) {
                var pwdWidget = elm.inheritedData('$formController')[attr.matchValidator];

                ctrl.$parsers.push(function(value) {
                    if (value === pwdWidget.$viewValue) {
                        ctrl.$setValidity('match', true); 
                        return value;
                    }                       

                    if (value && pwdWidget.$viewValue) {
                        ctrl.$setValidity('match', false);
                    }

                });

                pwdWidget.$parsers.push(function(value) {
                    if (value && ctrl.$viewValue) {
                        ctrl.$setValidity('match', value === ctrl.$viewValue);
                    }
                    return value;
                });
            }
        };
    }])

사용.

<input type="email" ng-model="value1" name="email" required>
<input type="email" ng-model="value2" name="emailConfirm" match-validator="email" required>

표시 오류

<div ng-if="[[yourFormName]].emailConfirm.$error">
    <div ng-if="[[yourFormName]].emailConfirm.$error.match">
        Email addresses don't match.
    </div>
</div>
   <input name="password" type="text" required="" ng-model="password" placeholder="password" class="ng-dirty ng-valid ng-valid-required">
   <input name="confirm_password" type="text" required="" ng-model="confirm_password" ui-validate=" '$value==password' " ui-validate-watch=" 'password' " placeholder="confirm password" class="ng-dirty ng-valid-required ng-invalid ng-invalid-validator"> 
   <span ng-show="form.confirm_password.$error.validator">Passwords do not match!</span>
        password errors: {
        "required": false,
        "validator": true
        }

이건 나한테 효과가 있었어.

지시:

modulename.directive('passwordCheck', 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

            var Value = null;

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


                validate();
            });

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

            var validate = function () {

                // values
                var val1 = Value;
                var val2 = attrs.passwordCheck;

                // set validity

                if (val1 != '' && val1 != undefined) {
                    ngModel.$setValidity('passwordCheck', val1 == val2);

                }

                else {
                    ngModel.$setValidity('passwordCheck', true);
                }
            };
        }
    }
});

HTML:

ng-model="confirmpassword.selected" type="password" name="confirmpassword" 

password-check="{{password.selected}}"

ng-show="resetpasswordform.confirmpassword.$error.passwordCheck && submitted" Password does not match

저도 같은 문제를 겪었습니다.저만의 디렉티브를 작성하려고 할 때, 이 추가 기능으로 수정했습니다.

ctrl.$validate();

여기서 ctrl은 ngModelController 입니다.

이것이 나의 견해이다.

<input type="password" match="signupCtrl.registrationData.password" name="confirmPassword" class="form-control" placeholder="Confirm Password" data-ng-model="signupCtrl.registrationData.confirmPassword" required>
        <span ng-messages="registerForm.confirmPassword.$error">
            <span ng-message="match">The Password must match</span>
        </span>

이게 내 지시야

(function () {
    'use strict';
    angular.module('matchDirective', [
        // Angular modules
        // Custom modules
        // 3rd Party Modules
    ]);
})(); 
(function () {
    'use strict';
    angular
        .module('matchDirective')
        .directive('match', match);
    match.$inject = ['$window'];

    function match($window) {
        // Usage:
        //     <element match="source"></element>
        // Creates:
        //
        var directive = {
            link: link,
            restrict: 'A',
            require: 'ngModel',
        };
        return directive;

        function link(scope, element, attrs, ctrl) {
            scope.$watch(attrs['match'], function (newVal, oldVal) {
                ctrl.$validators.match = function (modelValue, viewValue) {
                    if (newVal == modelValue) {
                        return true;
                    } else {
                        return false;
                    }
                }
                ctrl.$validate();
            });
        }
    }
})();

이런 게 나한텐 효과가 있어

js:

.directive('sameAs', function() { return {
    require : 'ngModel',
    link : function(scope, elm, attrs, ngModelCtrl) {

        ngModelCtrl.$validators.sameAs = function(modelValue, viewValue) {
            var checkedVal = attrs.sameAs;
            var thisInputVal = viewValue;

            if (thisInputVal == checkedVal) {
                return true; // valid
            } else {
                return false;
            }
        };
    }
}; });

html:

<input type="password" name="password" id="password" ng-model="password" />

<input type="password" name="passwordRepeat" id="passwordRepeat" 
    ng-model="passwordRepeat" same-as="{{password}}" />

KISS(Keep It Simple And Studpy) 원칙은 이 점에 유용할 수 있다.다음 절차를 수행하여 두 비밀번호가 일치하는지 여부를 보다 빠르고 쉽게 확인할 수 있습니다.

<div ng-app="app" ng-controller="passwordCheck">
  <form name="signUp" ng-submit="submitForm()" novalidate>
     <input type="password" name="password" ng-model="password" required>
     <input type="password" name="ConfirmPassword" ng-model="passwordconfirm"   required>
     <button type="submit"> Submit</button>
  </form>

  <hr>
  <span>Do they match?</span> {{signUp.password.$viewValue == signUp.confirmPassword.$viewValue}}
    </div>

양식을 제출하기 전에 js에서 이 작업을 수행할 수 있습니다.

var app = angular.module("app", []);
app.controller("passwordCheck", function($scope) {
   $scope.submitForm = function() {
      if ($scope.signUp.$valid && $scope.signUp.password.$viewValue == $scope.signUp.confirmPassword.$viewValue) {
            alert('Its a match!');
        };
};
});

JSfiddle에서도 테스트할 수 있습니다.

언급URL : https://stackoverflow.com/questions/14012239/password-check-directive-in-angularjs

반응형