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

HTML5 Input type=number ตัดศูนย์นำหน้า (Leading Zero) - วิธีแก้

ปัญหา

<input type="number"> จะตัดศูนย์นำหน้าออกอัตโนมัติ เช่น 00123 → 123 สร้างปัญหาสำหรับเบอร์โทร รหัสไปรษณีย์ หมายเลขบัตรประชาชน

วิธีแก้ไข

1. ใช้ type="tel" พร้อม pattern (แนะนำสำหรับเบอร์โทร) ✅

<input type="tel" pattern="[0-9]*">
  • iOS: แสดง numeric keyboard เต็มรูปแบบ
  • Android: แสดง numeric keyboard แต่ pattern อาจไม่บังคับได้เต็มที่
  • คงศูนย์นำหน้าได้ เพราะเป็น text input

2. ใช้ type="text" พร้อม pattern (รองรับทุกอุปกรณ์) ✅

<input type="text" pattern="[0-9]*" inputmode="numeric">
  • inputmode="numeric" - บอกเบราว์เซอร์แสดง numeric keypad
  • รองรับ iOS และ Android ทั้งคู่ดี
  • คงค่าทุกตัวอักษรได้ครบ

3. ใช้ type="text" พร้อม JavaScript validation

<input type="text" id="phone" maxlength="10">

<script>
document.getElementById('phone').addEventListener('input', function(e) {
  this.value = this.value.replace(/[^0-9]/g, '');
});
</script>

เปรียบเทียบ Input Types

Typeคง Leading ZeroKeyboard (iOS)Keyboard (Android)Validation
number❌NumericNumericBuilt-in
tel✅Numeric (full)NumericPattern only
text + pattern✅Numeric (with inputmode)NumericPattern + JS
text + inputmode✅NumericNumericJS only

แนะนำสำหรับกรณีต่างๆ

  • เบอร์โทรศัพท์: type="tel" pattern="[0-9]*"
  • รหัสไปรษณีย์: type="text" pattern="[0-9]{5}" inputmode="numeric"
  • บัตรประชาชน/บัตรเครดิต: type="text" pattern="[0-9]*" inputmode="numeric" + JS formatting
  • จำนวนนับทั่วไป: type="number" (ถ้าไม่ต้องการ leading zero)

ตัวอย่างสมบูรณ์สำหรับเบอร์โทรไทย

<input 
  type="tel" 
  pattern="[0-9]{10}" 
  maxlength="10"
  placeholder="08X-XXX-XXXX"
  title="กรอกเบอร์โทร 10 หลัก"
  required>