检测字符串是否为有效URL且不为空

时间:2016-01-27 14:10:41

标签: javascript angularjs

我想在js中执行此函数之前检查其中一个输入字段是否为空,以及#urlink是否为URL的格式:

$scope.favUrls.$add  

不确定如何去做。

HTML

<input type="text" id="urlName" class="form-control" placeholder=""  ng-model="mvName" />
<input type="text" id="urlLink" class="form-control" placeholder=""  ng-model="mvUrl" />

app.js

$scope.saveToList = function(event) {

    var mvName = $scope.mvName.trim();
    var mvUrl = $scope.mvUrl.trim();

          if (mvName.length > 0) {
            $scope.favUrls.$add({
              name: mvName,
              title: mvUrl
            });
              urlName.value = ''; //urlName is the ID of  input box - Angular rocks!
            urlLink.value = ''; //urlName is the ID of  input box - Angular rocks!
          }

}

1 个答案:

答案 0 :(得分:-2)

使用以下验证网址的功能

function ValidURL(str) {
  var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
    '((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
    '((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
    '(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
    '(\?[;&a-z\d%_.~+=-]*)?'+ // query string
    '(\#[-a-z\d_]*)?$','i'); // fragment locater
  if(!pattern.test(str)) {
    alert("Please enter a valid URL.");
    return false;
  } else {
    return true;
  }
}

source