2017-04-11 68 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