【问题标题】:URL validation. ng-pattern not working网址验证。 ng模式不起作用
【发布时间】:2016-06-06 17:38:15
【问题描述】:

$scope.regex = '^((http|https|ftp):\/\/)?([a-z]+\.)?[a-z0-9-]+(\.[a-z]{1,4}){1,2}(/.*\?.*)?$';

This is the regular expression i'm using to validate url, and its working fine. I have checked it on AngularJS website.
<div class="field_input">
  <div style="width: 100%;">
    <input type="text" name="website" ng-model="custom.websites" placeholder="www.daiict.ac.in" ng-minlength=3 ng-pattern="regex" required/>
  </div>
</div>
<div class="valid-chk" ng-show="requestForm1.website.$dirty" style="margin-top: 5px;">
  <i style="font-size: 1.15em;padding:0px;" ng-class="{'false':'icon-close', 'true': 'icon-correct'}[requestForm1.website.$valid]" class="icon-correct"></i>
</div>

这是我试图验证输入字段的html sn-p。 但是,这是行不通的。此外,当我在输入字段上使用 ng-pattern 时,除了必需之外,所有其他验证也不起作用。知道为什么...

【问题讨论】:

  • $scope.regex = /^((https?|ftp):\/\/)?([a-z]+\.)?[a-z0-9-]+(\.[a-z]{1,4}){1,2}(/.*\?.*)?$/i;
  • 我试过了。但还是不行
  • 必须在双引号内。如果没有,也尝试加倍反斜杠:$scope.regex = "/^((https?|ftp):\\/\\/)?([a-z]+\\.)?[a-z0-9-]+(\\.[a-z]{1,4}){1,2}(\\/.*\\?.*)?$/i"; 另外,调用ng-pattern="{{regex}}"
  • 我用过双引号。
  • 是的,它已经解决了。问题在于 ng-pattern="{{regex}}"。我没有使用花括号。感谢您的快速帮助

标签: jquery html angularjs regex validation


【解决方案1】:

您的ng-pattern="regex" 包含一个字符串regex 作为其值。为了引用真正的变量$scope.regex,需要使用模板语法:

ng-pattern="{{regex}}"

此外,由于模式是使用 字符串 定义的,因此您需要对反斜杠进行双重转义(请参阅a similar example code at the ngPattern reference page):

$scope.regex = '^((https?|ftp)://)?([A-Za-z]+\\.)?[A-Za-z0-9-]+(\\.[a-zA-Z]{1,4}){1,2}(/.*\\?.*)?$';

或者只是将它们放入一个字符类以避免任何歧义:

$scope.regex = '^((https?|ftp)://)?([a-z]+[.])?[a-z0-9-]+([.][a-z]{1,4}){1,2}(/.*[?].*)?$';

甚至可以传递RegExp 对象,因为这样您就可以使用不区分大小写的标志:

$scope.regex = "/^((https?|ftp):\\/\\/)?([a-z]+[.])?[a-z0-9-]+([.][a-z]{1,4}){1,2}(\\/.*[?].*)?$/i";

或者,可以使用 RegExp 构造函数定义与上述相同的表达式:

$scope.regex = RegExp('^((https?|ftp)://)?([a-z]+[.])?[a-z0-9-]+([.][a-z]{1,4}){1,2}(/.*[?].*)?$', 'i');

我还建议将http|https 缩短为https?

【讨论】:

  • 好吧,我想我已经完成了答案的编辑。请检查。
  • 有没有更好的正则表达式可以推荐?
  • 不知道你有什么样的要求。也许,您可以将(/.*[?].*)? 替换为/?.* 并使用([a-z]+[.])* 而不是([a-z]+[.])?。在我看来,这将匹配更多的 URL 并且执行得更快。
【解决方案2】:

可以使用new RegExp试试

new RegExp(pattern, option)

我使用i 作为忽略大小写的选项

$scope.regex = $scope.regex = new RegExp('^((https?|ftp)://)?([a-z]+[.])?[a-z0-9-]+([.][a-z]{1,4}){1,2}(/.*[?].*)?$', 'i');

PLUNKER DEMO

【讨论】:

  • 您的模式允许wwwdialectcom 输入。
  • 在我的例子中使用@Dreamer 模式不是我的
猜你喜欢
  • 2014-01-10
  • 1970-01-01
  • 2018-09-16
  • 2018-09-08
  • 1970-01-01
  • 2016-01-30
  • 2018-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多