Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

วิธี Validate URL Address ใน JavaScript (Regular Expression)

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 Approach (แนะนำสำหรับ Modern JS)

function isValidURLModern(url) {
  try {
    const parsed = new URL(url);
    return parsed.protocol === 'http:' || parsed.protocol === 'https:';
  } catch (e) {
    return false;
  }
}

// ทดสอบ
console.log(isValidURLModern('https://example.com'));  // true
console.log(isValidURLModern('https://localhost:3000')); // true (Valid per RFC)
console.log(isValidURLModern('javascript:alert(1)'));  // false (Protocol ไม่ใช่ http/https)
console.log(isValidURLModern('not a url'));            // false

ข้อควรพิจารณา

  • Regex ยาวซับซ้อน ยากต่อการบำรุงรักษา
  • URL Constructor ใช้งานง่ายกว่า แต่ยอมรับ URL ที่ Regex อาจไม่อนุญาต (เช่น localhost, IP)
  • ขึ้นอยู่กับ Use Case: Form Validation (Regex เข้มงวด), Internal Processing (URL Constructor)
  • Internationalized Domain Names (IDN/Unicode) ต้องใช้ Punycode หรือ Library เฉพาะ

สรุป

Validate URL ใน JavaScript ได้ 2 วิธีหลัก: 1) Regular Expression (ควบคุมรูปแบบได้ละเอียด เหมาะ Form Validation) 2) URL Constructor + try/catch (Modern, ใช้งานง่าย, Standards-compliant) เลือกใช้ตามความต้องการของโปรเจกต์

วิธีโค้ดข้อดี/ข้อเสีย
URL Constructor (Modern)new URL(url) + try/catchBuilt-in, Parse ได้ parts, แต่ accept 'https://localhost' และ 'https://1.2.3.4' (valid per spec)
HTML Anchor Elementconst a = document.createElement('a'); a.href = url; return a.protocol === 'http:' || a.protocol === 'https:'ใช้ Browser Parser, เร็ว แต่ lenient
Validator.js Libraryvalidator.isURL(url, options)Feature-rich, Options 多, ต้องติดตั้ง Package
RegExp (Custom)Pattern ด้านบนควบคุมได้ละเอียดที่สุด, ไม่ต้อง Dependency