Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Validate số thập phân (decimal) trong JavaScript


Regex /^[-+]?[0-9]+\.[0-9]+$/ kiểm tra số thập phân: dấu tùy chọn, ít nhất 1 chữ số, chấm, ít nhất 1 chữ số. Không khớp số nguyên (vd: 5).

Ví dụ

Kiểm tra input là số thập phân:

<!DOCTYPE html>
<html lang="vi">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Validate decimal JS</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result { font-size: 20px; font-weight: 500; }
  </style>
</head>
<body>
  <h1>Kiểm tra số thập phân trong JavaScript</h1>
  <div class="result"></div>
  <input type="text" class="num" placeholder="Nhập số..." />
  <button class="Btn">KIỂM TRA</button>
  <h3>Nhập số và nhấn KIỂM TRA</h3>
  <script>
    const resEle = document.querySelector(".result");
    document.querySelector(".Btn").addEventListener("click", () => {
      const str = document.querySelector(".num").value;
      const regex = /^[-+]?[0-9]+\.[0-9]+$/;
      const isDecimal = regex.test(str);
      resEle.textContent = isDecimal ? 'Là số thập phân hợp lệ' : 'KHÔNG phải số thập phân';
      resEle.style.color = isDecimal ? 'green' : 'red';
    });
  </script>
</body>
</html>

Kết quả

  • 123 -> Không (số nguyên)
  • 12.34 -> Có
  • -0.5 -> Có
  • .5 -> Không (thiếu số trước chấm)

Cải tiến: Cho phép .5 dùng /^[-+]?([0-9]*\.[0-9]+|[0-9]+\.?)$/ hoặc dùng Number() + !Number.isInteger().