Overwriting the AngularJS URL validator

后端 未结 3 1218
灰色年华
灰色年华 2021-01-18 08:45

AngularJS accepts this for a valid URL:

var URL_REGEXP = /^(ftp|http|https):\\/\\/(\\w+:{0,1}\\w*@)?(\\S+)(:[0-9]+)?(\\/|\\/([\\w#!:.?+=&%@!\\-\\/]))?$/;         


        
3条回答
  •  旧时难觅i
    2021-01-18 09:34

    As of Angular 1.3, it's relatively easy now that you can completely overwrite existing $validators:

    myApp.directive('input', function() {
        function link(scope, element, attrs, ngModel) {
            function allowSchemelessUrls() {
                // 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;
    
                // Silently prefixes schemeless URLs with 'http://' when 
                // converting a view value to model value.    
                ngModel.$parsers.unshift(function(value) {
                    if (!URL_REGEXP.test(value) && URL_REGEXP.test('http://' + value)) {
                        return 'http://' + value;
                    } else {
                        return value;
                    }
                });
    
                ngModel.$validators.url = function(value) {
                    return ngModel.$isEmpty(value) || URL_REGEXP.test(value);
                };
            }
    
            if (ngModel && attrs.type === 'url') {
                allowSchemelessUrls();
            }
        }
    
        return {
            require: '?ngModel',
            link: link
        };
    });
    

提交回复
热议问题