【问题标题】:Why does the regular expression not validate the website URL properly?为什么正则表达式不能正确验证网站 URL?
【发布时间】:2016-04-01 07:09:12
【问题描述】:

以下是我用来验证网站 URL 的 URL 表达式(正则表达式):

/(https?:\/\/)(www)?[A-Za-z0-9.\-@_~]+\.[A-Za-z]{2,}(:[0-9]{2,5})?(\/[A-Za-z0-9\/_\-.~?&=]*)*/

我的 Angular JS 代码实现如下:

 <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>

假设我提供了有效的 URL http://www.bharatividyapeeth.edu 它工作正常。 如果我输入无效的 URL,http://www. 会出现错误消息,但是当我输入无效的 URL 时,http://www.bharatividyapeeth 它不会显示错误消息并接受它作为有效的 URL。

有人可以更正我的代码以正确验证网站 URL 吗?

谢谢。

【问题讨论】:

标签: javascript angularjs regex url-validation


【解决方案1】:

您似乎想要一个更简单的regex 来完成您的任务。所以我只修改你的正则表达式。虽然这适用于大多数URLs,但在某些地方也会失败

/https?:\/\/(www\.)?(?!www\.)([A-Za-z0-9\-@_~]+\.)[A-Za-z]{2,}(:[0-9]{2,5})?(\.[A-Za-z0-9\/_\-~?&=]+)*/

【讨论】:

    【解决方案2】:

    这对我来说似乎是正确的:

    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];
    &lt;pre&gt;&lt;/pre&gt;

    【讨论】:

    • @WiktorStribiżew 我不擅长正则表达式。刚试了不知道好不好。
    【解决方案3】:

    请测试一下,看看这个正则表达式是否适合你:

    (https?:\/\/(?:www\.|(?!www))[^\s\.]+\.[^\s]{2,}|www\.[^\s]+\.[^\s]{2,})
    

    这将匹配以下内容:

    http://www.bharatividyapeeth.edu
    https://www.bharatividyapeeth.edu
    www.bharatividyapeeth.edu
    

    不匹配:

    http://www.bharatividyapeeth
    https://www.bharatividyapeeth
    www.bharatividyapeeth
    

    你可以在这里测试:

    http://regexr.com/

    【讨论】:

      猜你喜欢
      • 2014-09-15
      • 1970-01-01
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 2017-07-25
      • 1970-01-01
      相关资源
      最近更新 更多