title: Custom notPattern directive like ngPattern, but checking whether a RegExp does not match
body: <p>I am trying to write a custom AngularJS directive similar to ngPattern, except that this directive would fail validation if a RegExp does <em>not</em> match.</p>
  
  <p>Following <a href="https://github.com/angular/angular.js/blob/bfcf9946e16d21b55dde50d4d21c71c898b10215/src/ng/directive/validators.js#L23" rel="nofollow">the source</a> of the ngPattern directive, I came up with:</p>
  
  <pre><code>  .directive("notPattern", function () {
      return {
        restrict: "A",
        require: "?ngModel",
        link: function (scope, elem, attr, ctrl) {
          if (!ctrl) return;
  
          var regExp, notPatternExp = attr.notPattern;
          attr.$observe("notPattern", function (regex) {
            if (angular.isString(regex) &amp;&amp; regex.length &gt; 0) {
              regex = new RegExp("^" + regex + "$");
            }
  
            if (regex &amp;&amp; !regex.test) {
              var elemClone = angular.element(elem).clone();
              var elemHtml = angular.element("&lt;div&gt;").append(elemClone).html();
              throw new Error("Expected " + notPatternExp + " to be a RegExp but was " + regex + ". Element: " + elemHtml);
            }
  
            regExp = regex || undefined;
            ctrl.$validate();
          });
  
          ctrl.$validators.notpattern = function (value) {
            return ctrl.$isEmpty(value) || angular.isUndefined(regExp) || !regExp.test(value);
          };
        }
      };
    })
  </code></pre>
  
  <p>This works when I specify the regular expression source within the attribute, but I want to allow a <code>RegExp</code> object to be used directly, like ngPattern.</p>
  
  <p>The problem is that the expression is not being evaluated.</p>
  
  <p>Here is an example JSFiddle:<br>
  <a href="http://jsfiddle.net/8Lk3pqep/1/" rel="nofollow">http://jsfiddle.net/8Lk3pqep/1/</a></p>
  
  <p>In this example, entering anything other than "abc" into the text field will show "Invalid per 'pattern'!".  I expected to see "Invalid per 'notpattern'!" when "abc" is entered, but this appears only when I enter "testRegExp", thus indicating that the attribute value is not being evaluated.</p>
  
  <p>What am I doing wrong?</p>
  
  <p>I know that notPattern can be accomplished with ngPattern via something like:</p>
  
  <pre><code>$scope.testRegExp = {
    test: function (value) {
      return !/^abc$/.test(value);
    }
  };
  </code></pre>
  
  <p>.. but I would like to know why the custom directive is not evaluating the expression.</p>