如何使用javascript检测网址格式?

时间:2015-12-06 03:50:49

标签: javascript jquery

如何使用javascript检测网址格式?

我尝试使用我的代码但没有工作,有什么不对。

当我测试我的代码时,它不是警报。我该怎么办?

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.ValidURL(str)) 
  {
    alert("Please enter a valid URL.");
    //return false;
  } 
  else
  {
    alert("it's good");
    //return true;
  }
}

http://jsfiddle.net/18wz1xto/1/

2 个答案:

答案 0 :(得分:0)

在您当前的代码中 问题出在这里 问号未转义

您的代码

private int LineCount()
{
    int textLength = MainIOControl.TextLength;
    int lineCount = MainIOControl.Lines.Length - 1;
    return (textLength == 0 && lineCount == 0) ? 0 : lineCount;
}

更正后的代码:

'(\?[;&a-z\d%_.~+=-]*)?'+ // query string

这就是你得到错误和警报没有触发的原因。

工作代码here

它没有正确测试url因为需要调整正则表达式。

希望这有帮助!

答案 1 :(得分:0)

您的函数必须在引号'中传递参数,并且字符串中的正则表达式必须使用\再次转义\。看看here

<强> HTML:

<div onclick="ValidURL('http://www.google.com')">check url format</div>

<强> JS:

function ValidURL(str) {
  var pattern = new RegExp('^(https?:\\/\\/)?((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|((\\d{1,3}\\.){3}\\d{1,3}))(\\?[;&a-z\\d%_.~+=-]*)?(\\#[-a-z\\d_]*)?$','i'); // fragment locater
  if(!pattern.test(str)) 
  {
    alert("Please enter a valid URL.");
    //return false;
  } 
  else
  {
    alert("it's good");
    //return true;
  }
}
相关问题