title: Overwriting the AngularJS URL validator
body: <p>AngularJS accepts this for a valid URL:</p>
  
  <pre><code>var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&amp;%@!\-\/]))?$/;
  </code></pre>
  
  <p>Django accepts this:</p>
  
  <pre><code>regex = re.compile(
      r'^(?:http|ftp)s?://' # http:// or https://
      r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
      r'localhost|' #localhost...
      r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
      r'(?::\d+)?' # optional port
      r'(?:/?|[/?]\S+)$', re.IGNORECASE)
  </code></pre>
  
  <p>The main <strong>practical</strong> difference is that AngularJS accepts <code>http://some-host-without-tld</code>, while Django only allows <code>http://localhost</code> as a valid URL without TLD.</p>
  
  <p>Since it's problematic to overwrite the Django URL Validator, I want to overwrite the AngularJS validator. I attempted that this way, which works:</p>
  
  <pre><code>app.overwriteUrlValidator = function(ngModel) {
  
      // Django RegExp, ported to JS.
      var URL_REGEXP = /^(?:http|ftp)s?:\/\/(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|localhost|\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})(?::\d+)?(?:\/?|[\/?]\S+)$/gi;
  
      // Same validator as AngularJS's, only with a different RegExp.
      function urlValidator(value) {
          if (ngModel.$isEmpty(value) || URL_REGEXP.test(value)) {
              ngModel.$setValidity('url', true);
              return value;
          } else {
              ngModel.$setValidity('url', false);
              return undefined;
          }
      }
  
      // This is the part I'm not happy about. I need to use a timeout
      // because my code is executed before Angular adds its URL validator.
      // If I add mine before Angular does, it will not work for ??? reason.
      window.setTimeout(function() {
          ngModel.$formatters.push(urlValidator);
          ngModel.$parsers.push(urlValidator);
      }, 100);
  };
  
  
  /**
   * Keep track of user's interaction with input fields
   */
  app.inputDirective = function() {
      function link(scope, element, attrs, ngModel) {
          if (ngModel &amp;&amp; attrs.type === 'url') {
              app.overwriteUrlValidator(ngModel);
          }
      }
  
      return {
          restrict: 'A',
          require : '?ngModel',
          link    : link
      };
  };
  app.directive('input', app.inputDirective);
  app.directive('textarea', app.inputDirective);
  </code></pre>
  
  <p>I rather don't switch to another validation directive because I'd have to update and check a lot of code.</p>
  
  <p>Does anyone know a solid way of doing this?</p>