Dre*_*mer 2 html regex validation jquery angularjs
$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.Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
这是html片段,我试图验证输入字段.但这不起作用.此外,当我使用ng-pattern时,输入字段上的所有其他验证(除了必需)也不起作用.知道为什么......
您ng-pattern="regex"包含一个字符串regex作为其值.要引用实变量$scope.regex,您需要使用模板语法:
ng-pattern="{{regex}}"
Run Code Online (Sandbox Code Playgroud)
此外,由于模式是使用字符串定义的,因此需要双重转义反斜杠(请参阅ngPattern参考页面上的类似示例代码):
$scope.regex = '^((https?|ftp)://)?([A-Za-z]+\\.)?[A-Za-z0-9-]+(\\.[a-zA-Z]{1,4}){1,2}(/.*\\?.*)?$';
Run Code Online (Sandbox Code Playgroud)
或者只是将它们放入一个字符类中以避免任何歧义:
$scope.regex = '^((https?|ftp)://)?([a-z]+[.])?[a-z0-9-]+([.][a-z]{1,4}){1,2}(/.*[?].*)?$';
Run Code Online (Sandbox Code Playgroud)
或者甚至传递RegExp对象,因为你可以使用不区分大小写的标志:
$scope.regex = "/^((https?|ftp):\\/\\/)?([a-z]+[.])?[a-z0-9-]+([.][a-z]{1,4}){1,2}(\\/.*[?].*)?$/i";
Run Code Online (Sandbox Code Playgroud)
或者,可以使用RegExp构造函数定义与上面相同的表达式:
$scope.regex = RegExp('^((https?|ftp)://)?([a-z]+[.])?[a-z0-9-]+([.][a-z]{1,4}){1,2}(/.*[?].*)?$', 'i');
Run Code Online (Sandbox Code Playgroud)
我还建议缩短http|https到https?.