3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

AngularJSのカスタムバリデーションをモジュールに登録して使いまわす方法

Last updated at Posted at 2014-07-11

カスタムバリデーションのオブジェクトを、validationUtilsに集約して、使用するアプリケーションごとにディレクティブに登録すると便利なんじゃないかと思ったので、とりあえず書いてみました。

以下コード。

簡単にコピペで試せるように一つのHTMLにまとめてあります。

ajs.confirm.html
<!DOCTYPE html>
<html lang="ja"><head><meta charset="utf-8" /></head>
<body>
<div ng-app="app" ng-controller="confirmCtrl">
<form name="form" novalidate>
  <div>
    <input type="text" ng-model="target" name="target" />
    <input type="text" ng-model="targetConfirm" name="targetConfirm"
      confirm="target"
    />
  </div>
  <p ng-show="form.targetConfirm.$error.confirm">password confirmation invalid</p>
  <button ng-disable="form.$invalid">button</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script>
<script>
// commonUI.js
angular.module('commonUI',[]).
factory('validationUtils',[function(){
  return {
    confirm : {
      require : 'ngModel',
      scope : false,
      link : function(scope,elm,attr,ctrl){
        var confirm = function (viewValue) {
          var form = 'form';
          if(elm.length){
            form = elm[0].form.name;
          }else if(elm.context){
            form = elm.context.form.name;
          }
          var valid = viewValue != scope[form][attr.confirm].$viewValue;
          ctrl.$setValidity('confirm', !valid);
          if(!valid){ return viewValue; }
        };
        ctrl.$parsers.unshift(confirm);
        ctrl.$formatters.unshift(confirm);
      }
    }
  };
}]);
</script>

<script>
// app.js
var app = angular.module('app', ['commonUI']);
app.controller('confirmCtrl',['$scope',function ($scope) {
  $scope.target = 'abcd';
  $scope.targetConfirm = 'abcd';
}]);
app.directive('confirm',['validationUtils',function(validationUtils){
   return validationUtils.confirm;
}]);
</script>
</body></html>
3
3
1

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
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?