Search code examples
javascriptangularjsregexurl-validation

Why does the regular expression not validate the website URL properly?


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.


Solution

  • 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\/_\-~?&=]+)*/