I have this custom validation directive:
/** * Overwrites default url validation using Django URL validator * Original source: http://stackoverflow.com/questions/21138574/overwriting-the-angularjs-url-validator */ angular.module('dmn.vcInputUrl', []) .directive('vcUrl', function() { // Match Django URL validator, which allows schemeless urls. var URL_REGEXP = /^((?:http|ftp)s?:\/\/)(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[AZ]{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(); } } }; });
It works great when you "clutter up" the input by typing or pasting it, but I need to run this check by overwriting the default check type="url" when the value is initially set to ngModel.
I tried adding ngModel.$formatters.unshift(validator); but this leads to adding "http: //" to the input, which I need to avoid, as user changes are manually approved and it would be a waste of time to validate the addition from 'http: //'.
Any help would be appreciated!
source share