LoginSignup
1
1

More than 5 years have passed since last update.

[memo]AngularJsのDirectiveでパスワードとconfirmの比較をさせる。

Last updated at Posted at 2016-04-03
  • パスワードを変更した場合、確認用と比較して判定してくれる。
  • 確認用を変更した場合、パスワードと比較して判定してくれる。

こんな事をしてくれるディレクティブが欲しくなり、どこか公開してる方がいないか探してました。
一つのディレクティブで、上記二つを同時にしてくれるディレクティブを公開してるところが見当たらなかったので、簡単に作ってみたのでメモ。

HTML

<input type="text" name="password" ng-model="input.password" ng-minlength="8" ng-required="true">
<input type="text" name="passwordConfirm" ng-model="input.passwordConfirm" compare-with="input.password" ng-required="true">
<div ng-show="signUpForm.password.$touched && signUpForm.passwordConfirm.$touched" ng-messages="signUpForm.passwordConfirm.$error">
  <div ng-message="compareWith">Password Not Matched</div>
</div>

Directive

app.directive( 'compareWith', function (){
  return {
    require : "ngModel",
    scope   : {
      compareWith: '='
    },
    link:
      function( scope, element, attrs, ngModelCtrl ){

        scope.compare  = function( origin, value ){
          if( origin !== ngModelCtrl.$viewValue ){
            ngModelCtrl.$setValidity( 'compareWith', false );
          }else{
            ngModelCtrl.$setValidity( 'compareWith', true );
          }
          return value;

        };

        scope.$watch( 'compareWith', function( origin ){
          return scope.compare( origin, ngModelCtrl.$viewValue );
        } );

        ngModelCtrl.$parsers.unshift( function( viewValue ){
          return scope.compare( scope.compareWith, viewValue );;
        } );

      }
  };
} );

参考

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1