Validate URL ใน JavaScript ด้วย Regular Expression
ใช้ RegExp (Regular Expression) เพื่อตรวจสอบรูปแบบ URL ให้ถูกต้องตามมาตรฐาน (RFC 3986) คืนค่า true หากถูกต้อง, false หากไม่ถูกต้อง
Regex Pattern สำหรับ URL Validation (Comprehensive)
const urlPattern = new RegExp(
'^(https?:\\/\\/)?' + // Protocol (https:// or https://) - Optional
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' + // Domain name (example.com)
'((\\d{1,3}\\.){3}\\d{1,3}))' + // OR IP Address (v4) (192.168.1.1)
'(\\:\\d+)?' + // Port (:80, :443) - Optional
'(\\/[-a-z\\d%_.~+]*)*' + // Path (/path/to/resource) - Optional
'(\\?[;&a-z\\d%_.~+=-]*)?' + // Query String (?key=value&foo=bar) - Optional
'(\\#[-a-z\\d_]*)?$', 'i' // Fragment (#section) - Optional, Case Insensitive
);
ฟังก์ชัน Validate URL พร้อมใช้งาน
function isValidURL(url) {
const pattern = new RegExp(
'^(https?:\\/\\/)?' +
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' +
'((\\d{1,3}\\.){3}\\d{1,3}))' +
'(\\:\\d+)?' +
'(\\/[-a-z\\d%_.~+]*)*' +
'(\\?[;&a-z\\d%_.~+=-]*)?' +
'(\\#[-a-z\\d_]*)?$', 'i'
);
return pattern.test(url);
}
// ทดสอบ
console.log(isValidURL("https://example.com")); // true
console.log(isValidURL("https://www.example.com")); // true
console.log(isValidURL("https://sub.domain.co.uk/path?query=1#hash")); // true
console.log(isValidURL("https://192.168.1.1:8080")); // true
console.log(isValidURL("ftp://example.com")); // false (Protocol ไม่รองรับ)
console.log(isValidURL("example.com")); // true (Protocol Optional)
console.log(isValidURL("not a url")); // false
ตัวอย่าง HTML ทดสอบ
<!DOCTYPE html>
<html>
<body>
<script>
var myURL;
function validURL(myURL) {
var pattern = new RegExp('^(https?:\\/\\/)?' +
'((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|' +
'((\\d{1,3}\\.){3}\\d{1,3}))' +
'(\\:\\d+)?' +
'(\\/[-a-z\\d%_.~+]*)*' +
'(\\?[;&a-z\\d%_.~+=-]*)?' +
'(\\#[-a-z\\d_]*)?$', 'i');
return pattern.test(myURL);
}
document.write(validURL("https://qries.com")); // true
</script>
</body>
</html>
วิธีอื่นๆ ในการ Validate URL
| วิธี | โค้ด | ข้อดี/ข้อเสีย |
|---|---|---|
| URL Constructor (Modern) | new URL(url) + try/catch | Built-in, Parse ได้ parts, แต่ accept 'https://localhost' และ 'https://1.2.3.4' (valid per spec) |
| HTML Anchor Element | const a = document.createElement('a'); a.href = url; return a.protocol === 'http:' || a.protocol === 'https:' | ใช้ Browser Parser, เร็ว แต่ lenient |
| Validator.js Library | validator.isURL(url, options) | Feature-rich, Options 多, ต้องติดตั้ง Package |
| RegExp (Custom) | Pattern ด้านบน | ควบคุมได้ละเอียดที่สุด, ไม่ต้อง Dependency |