Validate URL with AngularJS and HTML 5

26,986

Solution 1

Instead of binding the regex to scope, you could directly add the regex to ng-pattern attribute. Like this:

<input type="text" ng-pattern="/^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/" ng-model="website">

I have updated the plunkr. Please take a look at this. Plukr

Solution 2

The thing here is, if you want to bind ng-pattern from controller, your regex shouldn't contain the starting and ending /s. Like this:

$scope.regex = "^(http[s]?:\\/\\/){0,1}(www\\.){0,1}[a-zA-Z0-9\\.\\-]+\\.[a-zA-Z]{2,5}[\\.]{0,1}$"

But, if you directly specify pattern like ng-pattern="/^(http|https|...)$/", you need the extra /s as well.

working plunker

Share:
26,986
MarcosF8
Author by

MarcosF8

Updated on July 09, 2022

Comments

  • MarcosF8
    MarcosF8 almost 2 years

    Good morning all:

    Looks like a very common question, but after googling for hours I am not able to figure this out: how to validate an URL including www without http.

    These is what I did:

    1. Used the input type url: it does not accept www.google.com;
    2. Changed the input type to text and used ng-pattern: I still get the www.google.com invalid;
    3. Changed different regex but still not working.

    So when I click on the submit button, I show an alert if the form is invalid (true invalid, false valid). Here is my Plunker

    Thanks for the help