Angularjs - 使用自定义指令验证初始 url 值

Angularjs - Validate initial url value with custom directive

本文关键字:url 验证 指令 自定义 Angularjs      更新时间:2023-09-26

我有这个自定义验证指令:

/**
 *  Overwrites default url validation using Django's URL validator
 *  Original source: http://stackoverflow.com/questions/21138574/overwriting-the-angularjs-url-validator
 */
angular.module('dmn.vcInputUrl', [])
.directive('vcUrl', function() {
  // Match Django's URL validator, which allows schemeless urls.
  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+)$/i;
  var validator = function(value) {
    if (!URL_REGEXP.test(value) && URL_REGEXP.test('http://' + value)) {
      return 'http://' + value;
      } else {
        return value;
      }
    }
  return {
    require: '?ngModel',
    link: function link(scope, element, attrs, ngModel) {
      function allowSchemelessUrls() {

        // Silently prefixes schemeless URLs with 'http://' when converting a view value to model value.    
        ngModel.$parsers.unshift(validator);
        ngModel.$validators.url = function(value) {
          return ngModel.$isEmpty(value) || URL_REGEXP.test(value);
        };
      }
      if (ngModel && attrs.type === 'url') {
        allowSchemelessUrls();
      }
    }
  };
});

当您通过键入或粘贴"弄脏"输入时,它可以正常工作,但我需要它来运行此验证,在最初在 ngModel 中设置值时覆盖默认type="url"验证。

我尝试添加ngModel.$formatters.unshift(validator);但它会导致"http://"被添加到输入中,我需要避免这种情况,因为用户的更改是手动批准的,批准添加"http://"会浪费时间。

任何帮助将不胜感激!

在输入类型字段上设置 ng-model-options,例如:

<input type="text"
ng-model-options="{ updateOn: 'default', debounce: {'default': 0} }"</input>

这将确保您的验证器"最初在ngModel中设置值时"被触发,正如您在问题中所述。

在ngModel选项上查看详细的AngularJs文档:在此处输入链接说明

Url 的验证

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<form name="form">
      URL: <input type="url" ng-model="url.text"  placeholder="Enter Link" name="fb_link"></input>
 <span class="error" ng-show="form.fb_link.$error.url"></span>
</form>