idealboy
idealboy

Reputation: 213

Disable Angular Form Validation on single input (url)

I'm building an Angular form with a URL field that can be formatted either with a prefix (http://) or without. Using Angular's default url validation requires http://, so I plugged in the following regex, which accepts with and without a prefix:

<input type="text" id="siteAddress" name="siteAddress" ng-model="user.url" ng-pattern="/^(https?:\/\/)?([\dA-Za-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/" required>

This works great, but when I set type="url", Angular's validation overwrites my custom ng-pattern. This form is for mobile users only, so the type="url" is important so that they receive the correct keyboard, and so their mobile OS does not attempt to autocorrect their input.

Is it possible to use type="url" without Angular applying its default validation, or is it possible to modify Angular's default validation so that it accepts no url prefix?

Thanks!

Upvotes: 4

Views: 6465

Answers (2)

GRaAL
GRaAL

Reputation: 626

It seems like there is no official API to do that but you always can override default directive or use your directive with higher priority to change the standard behavior.

For example, angular's input directive gets the type from $attributes object, so you may remove this attribute.

directive('ignoreType', function() {
    return {
        priority: 500,
        compile: function(el, attrs) { 
            attrs.$set('type', 
                null,                //to delete type from attributes object
                false                //to preserve type attribute in DOM
            );
        }
    }
});

Here is jsfiddle for it.

Of course this solution may also break behavior of other directives which work with type attribute, so use it carefully.

Upvotes: 3

Fedaykin
Fedaykin

Reputation: 4552

An idea would be to test the $removeControl method from the FormController to see if the native url validation would go off... http://docs.angularjs.org/api/ng.directive:form.FormController

Inside your controller you would do something like this:

    $scope.form.$removeControl('siteAddress');

Im not sure exactly what it will do, since I haven't got the chance to test it out and the docs about this are incomplete... let me know if this works please.

Hope that could give you some help.

Upvotes: 0

Related Questions