jquery - 网址验证。 ng 模式不起作用

标签 jquery html angularjs regex validation

$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 片段。 但是,这是行不通的。此外,当我在输入字段上使用 ng-pattern 时,除了必需的所有其他验证也不起作用。知道为什么...

最佳答案

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

ng-pattern="{{regex}}"

此外,由于模式是使用 string 定义的,因此您需要对反斜杠进行双重转义(参见 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?

关于jquery - 网址验证。 ng 模式不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35602017/

相关文章:

Javascript 不适用于最大/最小按钮?

css - 如何让我的菜单栏不超出屏幕?

javascript - 在(IE 和 Chrome)中使用双显示器时查找显示器的分辨率

angularjs - ng-show 不适用于自定义指令

javascript - Angular : show a message when no results in angular ng-repeat ?(具体情况)

angularjs - 使用HTML FIleSystem API将文件从src移动到dest

javascript - JQuery - 如何发送表单并调用 anchor ?

jquery - 如何在Jquery中使用标签类获取div类

jquery - HTML 解析 - 从 div 内的表中获取数据?

jquery - 使用jQuery从右向左滑动div