Sử dụng isNaN() (is Not a Number) để kiểm tra giá trị có phải số không. Trả về true nếu KHÔNG phải số.
Ví dụ
<!DOCTYPE html>
<html lang="vi">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kiểm tra số</title>
</head>
<body>
<form name="checkingInput" onsubmit="return checkInputIsNumber()">
Nhập giá trị: <input type="text" name="txtValue"> <br>
<input type="submit" value="Kiểm tra">
</form>
<script>
function checkInputIsNumber() {
var value = document.forms["checkingInput"]["txtValue"].value;
if (isNaN(value)) {
alert("Vui lòng nhập số!");
return false; // Hủy submit
}
return true;
}
</script>
</body>
</html>
Cách chạy
Lưu index.html, mở Live Server, nhập chữ/số và nhấn Kiểm tra.
Kết quả
- Nhập "abc" → Alert "Vui lòng nhập số!", form không submit
- Nhập "100" → Form submit bình thường
Lưu ý: isNaN("") trả về false (coerce thành 0). Dùng Number.isNaN() hoặc value.trim() === "" để kiểm tra chặt hơn.