2017-04-11 67 views
1

早上好一切:验证URL用角和HTML 5

看起来像一个非常普遍的问题,但对于谷歌搜索小时后,我无法想出解决办法:如何验证包括www没有http的URL。

这是我做过什么:

  1. 使用的输入型网址:它不接受www.google.com;
  2. 更改输入类型为text并使用ng-pattern:我仍然得到www.google.com无效;
  3. 更改了不同的正则表达式,但仍然无法正常工作。

所以当我点击提交按钮时,如果窗体无效(true无效,false有效),我会显示警报。这里是my Plunker

感谢您的帮助

+1

https://www.npmjs.com/package/angular-validation – Charly

+0

http://stackoverflow.com/a/8234912/3110058使用该模式在这个它是在你的pluncker工作的罚款。 模式是 /((([A-Za-z] {3,9}:(?:\/\ /)?)(?:[ - ;:&= \ + \ $,\ w] + @ ?)[A-ZA-Z0-9 .-] + |(:万维网?|。[ - ;:&= \ + \ $,\ W] + @)[A-ZA-Z0-9 .-] + )((:\/[\ +〜%\/\ W -_。] *?)\ ??(:[ - \ + =&;%@ \ W _。] *?)#(:???[ \ w] *))?)/ –

回答

3

而是结合了正则表达式的范围,你可以直接在正则表达式添加到ng-pattern属性。像这样:

<input type="text" ng-pattern="/^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/" ng-model="website"> 

我已经更新了plunkr。请看看这个。 Plukr

+0

谢谢你,它工作的很好! – MarcosF8

0

这里试试这个例子

<!DOCTYPE html> 
 
<html> 
 
<head> 
 

 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 
    <script type="text/javascript"> 
 

 

 
    angular.module("app",[]) 
 
    .controller("ctrl",function($scope){ 
 
     $scope.checkIfUrl = function(){ 
 

 
     $scope.isPresent = false; 
 

 
     if ($scope.inputValue != undefined && $scope.inputValue != null) { 
 
      var url = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/; 
 
      var Link = $scope.inputValue; 
 
      if (Link != "" && Link != undefined && url.test(Link)) { 
 
      if (Link.indexOf("http") != 0) { 
 
       Link = "http://" + Link; 
 
      } 
 
      $scope.isPresent = true; 
 
      } 
 
     } 
 

 
     }; 
 

 
     $scope.hyperlinkClick= function(){ 
 
     var Link = "http://" + $scope.inputValue; 
 
     console.log(Link); 
 
     window.open(Link); 
 

 
     }; 
 
    }) 
 

 
    </script> 
 
</head> 
 
<body ng-app="app" ng-controller="ctrl"> 
 
    <input type="text" ng-model="inputValue"> 
 

 
    <button ng-click="checkIfUrl()"> check If Url</button> 
 

 
    <a ng-if="isPresent" style="color: blue; cursor: pointer;" ng-click="hyperlinkClick()">{{inputValue}}</a> 
 

 
    <span style="color: black" ng-if="!isPresent">{{inputValue}}</span> 
 

 
</body> 
 
</html>

+0

非常感谢! – MarcosF8

3

的事情是,如果你要绑定ng-pattern从控制器,您正则表达式应该不包含起始和结束/秒。就像这样:

$scope.regex = "^(http[s]?:\\/\\/){0,1}(www\\.){0,1}[a-zA-Z0-9\\.\\-]+\\.[a-zA-Z]{2,5}[\\.]{0,1}$" 

但是,如果你直接使用像ng-pattern="/^(http|https|...)$/"模式,你需要额外的/ S以及。

working plunker

+0

谢谢!我用基本概念来帮助我。它仍然对这个URL有效:fdsfsfsfsf – MarcosF8

+0

@ MarcosF8忘记了逃脱斜线。现在工作。更新的运动员也:) – tanmay