Angularjs - checking source URL value using custom directive

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!

0
source share
2 answers

Set the ng-model parameters in the input type field, for example:

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

This ensures that your validator is launched "when the value is initially set to ngModel", as you said in the question.

See AngularJs detailed document on ngModelOptions: enter link description here

0
source

URL check:

 <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> 
-2
source

All Articles