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:
www.google.com
;text
and used ng-pattern
: I still get the www.google.com
invalid;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
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With