Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate URL with AngularJS and HTML 5

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

like image 895
MarcosF8 Avatar asked Apr 11 '17 09:04

MarcosF8


2 Answers

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

like image 71
Muhammed Neswine Avatar answered Nov 03 '22 08:11

Muhammed Neswine


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

like image 36
tanmay Avatar answered Nov 03 '22 10:11

tanmay