站內搜尋

Wednesday, March 25, 2020

[JavaScript] 如何檢查表單的內容是否為 數字、整數、正整數

假設表單(form)上有一個欄位是年齡,如下:

年齡:<input type="text" name="age" id="age">

因為年齡一定是正整數,如何在使用者送出(submit)時檢查呢?很簡單...



age = document.getElementById("age").value;
if (isNaN(age)) {
    alert("Age需為數字");
    return false;
}
if (!Number.isInteger(+age)) {
    alert("Age需為整數");
    return false;
}
if (+age < 0) {
    alert("Age需為正數");
    return false;
}

No comments:

Post a Comment