function isValidUrl(str) {
// 僅檢查開頭為 https:// 或 https:// 且包含非空白字元
var regex = /^https?:\/\/\S+$/i;
return regex.test(str);
}
// 使用
var url = document.getElementById('urlInput').value;
if (!isValidUrl(url)) {
alert('請輸入有效的 URL(以 https:// 或 https:// 開頭)');
}
var urlRegex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!-)[\w-]{1,63}(?
涵蓋:協定、可選認證、網域/IP、連接埠、路徑/查詢/片段。
function isValidUrlModern(str) {
try {
var u = new URL(str);
return u.protocol === 'http:' || u.protocol === 'https:';
} catch (e) {
return false;
}
}
core-js 或 url-polyfill)。<form onsubmit="return isValidUrl(this.url.value)">
<input name="url" type="url" required placeholder="https://example.com">
<button type="submit">送出</button>
</form>
HTML5 type="url" 瀏覽器會做基本驗證,但規則較寬鬆,建議搭配 JS 二次檢查。