Reputation: 12957
The following is the URL expression(regex) I'm using to validate website URL :
/(https?:\/\/)(www)?[A-Za-z0-9.\-@_~]+\.[A-Za-z]{2,}(:[0-9]{2,5})?(\/[A-Za-z0-9\/_\-.~?&=]*)*/
My angular JS code implementation is as follows :
<md-input-container class="md-block" style="margin-top:20px;">
<label>Website</label>
<input ng-model="schoolDetails.website" name="website" ng-change="editField()" type="url" ng-pattern="/(https?:\/\/)(www)?[A-Za-z0-9.\-@_~]+\.[A-Za-z]{2,}(:[0-9]{2,5})?(\/[A-Za-z0-9\/_\-.~?&=]*)*/">
<div ng-messages="schoolDetailsForm.website.$error">
<div ng-message="pattern">Please enter a valid website</div>
</div>
</md-input-container>
Suppose I give valid URL http://www.bharatividyapeeth.edu
it works fine.
If I give the invalid URL, http://www.
the error message appears, but when I enter the invalid URL, http://www.bharatividyapeeth
it doesn't show me the error message and accepts it as a valid URL.
Can some one please correct my code in order to properly validate the website URL?
Thanks.
Upvotes: 1
Views: 1076
Reputation: 11032
It seems you want a simpler regex
for your task. So I am modifying your regex only. While this will work for most URLs
but will also fail at some places
/https?:\/\/(www\.)?(?!www\.)([A-Za-z0-9\-@_~]+\.)[A-Za-z]{2,}(:[0-9]{2,5})?(\.[A-Za-z0-9\/_\-~?&=]+)*/
Upvotes: 1
Reputation: 197
Please test and see if this regex will work for you:
(https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})
This one will match the following:
http://www.bharatividyapeeth.edu
https://www.bharatividyapeeth.edu
www.bharatividyapeeth.edu
Will not match:
http://www.bharatividyapeeth
https://www.bharatividyapeeth
www.bharatividyapeeth
You can test here:
Upvotes: 0
Reputation: 74738
This seems to be correct to me:
var str = 'http://www.bharatividyapeeth.in'
var reg = /(http|https)(:\/\/)+?(w{3}(\.\w*\.))+(edu|com|co\.in|in)/gi;
document.querySelector('pre').innerHTML = str.match(reg)[0];
<pre></pre>
Upvotes: 1