Sử dụng Regular Expression (Regex)
Regex phức tạp nhưng linh hoạt. Dưới đây là pattern phổ biến (RFC 3986 simplified).
Ví dụ hàm validate
<!DOCTYPE html>
<html>
<body>
<script>
function validURL(str) {
var pattern = new RegExp(
'^(https?:\\/\\/)?' + // protocol
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // domain
'((\\d{1,3}\\.){3}\\d{1,3}))' + // hoặc IP v4
'(\\:\\d+)?(\\/[-a-z\\d%_.~+]*)*' + // port + path
'(\\?[;&a-z\\d%_.~+=-]*)?' + // query string
'(\\#[-a-z\\d_]*)?$', 'i' // fragment
);
return pattern.test(str);
}
document.write(validURL("https://qries.com")); // true
document.write("<br>" + validURL("https://sub.domain.co.uk/path?query=1#hash")); // true
document.write("<br>" + validURL("not-a-url")); // false
document.write("<br>" + validURL("ftp://files.com")); // false (chỉ http/https)
</script>
</body>
</html>
Cách hiện đại: URL Constructor (ES2015+)
function isValidURL(string) {
try {
new URL(string);
return true;
} catch (_) {
return false;
}
}
// Yêu cầu protocol cho URL tuyệt đối
isValidURL("https://example.com"); // true
isValidURL("example.com"); // false (thiếu protocol)
// Cho phép relative: new URL(string, "https://base.com")
So sánh
| Phương pháp | Ưu điểm | Nhược điểm |
|---|---|---|
| Regex | Kiểm soát chi tiết, không cần protocol | Phức tạp, khó maintain, false positive/negative |
| URL API | Đơn giản, chuẩn web, parse tự động | Bắt buộc protocol (trừ khi có base), IE không hỗ trợ |
Khuyến nghị
- Dùng
new URL()cho validation cơ bản (hiện đại, ít bug). - Dùng Regex khi cần quy tắc tùy chỉnh (chỉ cho phép domain nhất định, cấm IP...).
- Luôn validate/server-side – client-side chỉ để UX.