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.
Author by
MarcosF8
Updated on July 09, 2022Comments
-
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
withouthttp
.These is what I did:
- Used the input type url: it does not accept
www.google.com
; - Changed the input type to
text
and usedng-pattern
: I still get thewww.google.com
invalid; - 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
- Used the input type url: it does not accept