Question

In a custom validation directive I ensure that the entered value does not conflict with others in the database. If it does, I would like to tell the user not only that there's a conflict, but also the name of the item it is conflicting with.

Storing these details in the scope would probably work, but doesn't seem right to me at all. Is there a better way?

Directive:

angular.module('myApp')
  .directive('conflictcheck', function (myServer) {
    return {
      require: 'ngModel',
      link: function (scope, elm, attrs, ctrl) {
        ctrl.$parsers.unshift(function (viewValue) {
          var conflict = myServer.getConflict(viewValue);
          if (!conflict) {
            ctrl.$setValidity('conflictcheck', true);
            return viewValue;
          } else {
            ctrl.$setValidity('conflictcheck', false);

            // pass additional info regarding the conflict here

            return undefined;
          }
        });
      }
    };
  });

View:

<form name="myform" action="#">
  <input ng-model="foo" conflictcheck />
  <div ng-if="myform.foo.$error.conflictcheck">
     Error: Foo conflicts with XXXXXXXX!
  </div>
</form>
Was it helpful?

Solution

Validation errors are handled by FormController so it's reasonable to keep all validation-related data inside the form object itself. This could be implemented by attaching arbitrary data to myform instance:

app.factory('myServer', function(){
  return {
    getConflict: function(viewValue){
      var comparedAgainst = 'existing@email.com';
      if(viewValue === comparedAgainst){
        return comparedAgainst;
      }
    }
  }
});

app
  .directive('conflictcheck', function (myServer) {
    return {
      require: ['ngModel', '^form'],
      link: function (scope, elm, attrs, ctrls) {
        var ngModelCtrl = ctrls[0];
        var ngFormCtrl = ctrls[1];

        ngModelCtrl.$parsers.unshift(function (viewValue) {
          // getConflict returns conflicting value
          var conflict = myServer.getConflict(viewValue);

          if (!conflict) {
            ngModelCtrl.$setValidity('conflictcheck', true);
            return viewValue;
          } else {
            ngModelCtrl.$setValidity('conflictcheck', false);
            // We attach validation-specific data to arbitrary data property
            ngFormCtrl.foo.data = {
              conflictcheck: conflict
            };

            return undefined;
          }
        });
      }
    };
  });
<form name="myform" novalidate>
  Email: 
  <input ng-model="foo" name="foo" conflictcheck />
  <div ng-show="myform.foo.$error.conflictcheck">
   Error: Foo conflicts with {{myform.foo.data.conflictcheck}}!
  </div>
</form>

Plunker

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top