簡體   English   中英

驗證數字輸入總是返回一個數字作為值

[英]Validating a numeric input always returns a number as a value

我正在編寫一段代碼來檢查數字輸入。 如果輸入為空,則其值將設置為0 稍后,它將檢查輸入是否只包含數字或是否包含其他字符:然后它會發出警報並說明輸入是否有效(數字)或無效(包含其他字符)。

問題是,即使我在輸入字段中插入字母,輸入也始終被視為0 如果我刪除檢查輸入是否為空的塊,代碼的 rest 將按預期工作。

預先感謝您,對於菜鳥問題深表歉意。

 const input = document.getElementById("input"); const calculate = document.getElementById("calculate"); calculate.addEventListener("click", function() { let inputValue = input.value; // Check if the input if empty; if it is, assign to it zero // Removing this if block will make everything else work fine if (inputValue === "") { // inputValue = '0'; } else { inputValue = inputValue; } //This line is useless, but will be implemented in a function so I kept it for debugging purposes // Check if the input contains only numbers let numbers = /^[0-9]+$/; if ( inputValue.match(numbers) ) { alert(`Your input is valid. The number: ${inputValue}`) } else { alert(`Your input is not valid. The input: ${inputValue}`) } });
 <h3>Insert a number or leave blank for Zero<h3> <input type="number" id="input" placeholder="Insert number" style> <input type="button" value="calculate" id="calculate">

我認為問題是“輸入類型=數字”強制瀏覽器只接受數字作為有效值。 不幸的是,其他字符也被接受似乎是一個錯誤: https://bugzilla.mozilla.org/show_bug.cgi?id=1398528

如果您將輸入更改為鍵入文本,則您的代碼可以正常工作。唉,這也不是一個好的解決方案。

如果您使用的是 input type="number"

  1. 如果提供的值不是浮點數,您將始終得到一個空字符串。

    前任。 12+ //"" 空

  2. 如果您將輸入作為有效的浮點數輸入,您將始終得到一個浮點數

    前任。 +12 // 12

    12 // 12

值清理算法如下:如果元素的不是有效的浮點數,則將其設置為空字符串。

通過指定類型 ( <input type="number"> ),您要求瀏覽器僅接受數字。 如果你想接受非數字輸入並用它做一些事情,你必須使用 ( <input type="text"> ) 並解析內容並自己進行驗證。

所以在你的情況下

// Check if the input contains only numbers 如果用戶輸入的不是浮點數,代碼永遠不會觸發。

如果要將 "" 視為 0:

const inputValue = +input.value;
   // 0          = "";
   // 12         = 12;
   // 12         = +12;
   // 0          = 12+ // since not a valid number

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM