<form>
<input type="url" name="url" placeholder="https://example.com" required>
<button type="submit">送出</button>
</form>
瀏覽器自動檢查格式,但規則較寬鬆(允許 https://localhost 等)。
function isValidURL(str) {
// RFC 3986 簡化版:協議 + 域名/IP + 可選埠/路徑/查詢/片段
var pattern = /^(https?:\/\/)?/ // 協議 (可選)
+ /(([a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}|localhost)/ // 域名或 localhost
+ /(:\d+)?/ // 埠號
+ /(\/[^\s]*)?$/; // 路徑等
return pattern.test(str);
}
// 測試
isValidURL('https://www.example.com'); // true
isValidURL('https://localhost:3000/path'); // true
isValidURL('ftp://example.com'); // false (非 http/https)
isValidURL('example.com'); // true (允許無協議)
isValidURL('not a url'); // false
function isStrictURL(str) {
var pattern = /^https?:\/\//i // 必須 http/https
+ /(?:[a-zA-Z0-9-]+\.)+[a-zA-Z]{2,}/ // 域名
+ /(?::\d+)?/ // 可選埠
+ /(?:(?:\/|\\?|#)[^\s]*)?$/; // 路徑/查詢/錨點
return pattern.test(str);
}
<form id="urlForm" onsubmit="return checkUrl()">
<input type="text" id="url" name="url" placeholder="請輸入完整網址 (含 https://)">
<span id="urlError" class="error" style="display:none;color:red"></span>
<button type="submit">提交</button>
</form>
<script>
function checkUrl() {
var url = document.getElementById('url').value.trim();
var $err = document.getElementById('urlError');
if (!url) { $err.textContent = '網址不可為空'; $err.style.display = 'block'; return false; }
if (!isStrictURL(url)) { $err.textContent = '格式錯誤,需包含 https:// 或 https://'; $err.style.display = 'block'; return false; }
$err.style.display = 'none';
return true; // 允許提交
}
</script>
400, 'msg' => '無效的網址']));
}
// 進一步處理:file_get_contents、cURL 抓取、存入資料庫...
10.x.x.x、172.16-31.x.x、192.168.x.x、127.0.0.1、169.254.x.x (metadata service)。file://、gopher://、dict:// 等非 HTTP 協議。CURLOPT_FOLLOWLOCATION 限制重導向次數與域名。
try {
var u = new URL(input); // 必須含協議
console.log('協議:', u.protocol); // 'https:'
console.log('主機:', u.hostname); // 'example.com'
console.log('埠:', u.port); // '443' 或 ''
console.log('路徑:', u.pathname); // '/path'
console.log('查詢:', u.search); // '?a=1'
console.log('雜湊:', u.hash); // '#section'
} catch (e) {
// 格式無效
}