3

这个脚本应该检查提交的值是否是一个 Url,但它不这样做。我对正则表达式不太熟悉,我为我做这个的朋友出去旅行了。

      <script type="text/javascript">// <![CDATA[
       window.onload=init;

        function init(){
        document.forms[0].onsubmit= function (){
        var url= document.getElementById("url").value;
        var desc= document.getElementById("description").value;
        var regex=new RegExp("^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$");
        var match=regex.test(url);
        if(!match)
        {
            alert("The URL you entered is not valid");
            return false;
        }
        if(desc.length<10)
        {
            alert("There must be at least 10 characters in the description");
            return false;
        }
    };
}
  // ]]></script>
4

3 回答 3

6

PHP 5 有一个内置函数。你可以用filter_var()它来做。

function is_url($url)
{
    return filter_var($url, FILTER_VALIDATE_URL) !== false;
}

编辑:客户端验证只是为用户提供便利。它实际上并没有验证数据,我可以使用 Firefox TamperData 向您提交我想要的任何内容。您应该如上所示进行服务器验证。

于 2012-09-23T05:51:48.590 回答
0
if(/^([a-z]([a-z]|\d|\+|-|\.)*):(\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?((\[(|(v[\da-f]{1,}\.(([a-z]|\d|-|\.|_|~)|[!\$&'\(\)\*\+,;=]|:)+))\])|((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=])*)(:\d*)?)(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*|(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)|((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)){0})(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(\#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?\/$/i.test(url)) {
    alert("URL is valid");
}
else {
    alert("URL is not valid");
}

来源:这里

于 2012-09-23T05:46:11.257 回答
0

我建议你开始学习正则表达式。他们学起来很有趣。我目前也在学习它们。Jeffrey EF Friedl 的 O'reilly 的 Mastering Regular Expressions是一本非常好的书,您可以从一些网站免费下载。一探究竟。

于 2012-09-23T05:51:35.200 回答