gpt4 book ai didi

javascript - 我如何判断 <input type=number> 是空白还是具有无效值?

转载 作者:数据小太阳 更新时间:2023-10-29 04:16:32 28 4
gpt4 key购买 nike

如果用户在 <input type=number> 中键入无效值(例如:“1.2.3”) , 然后 Chrome 和 Firefox 报告 <input>value属性为 ""而不是 "1.2.3" .

那么,我如何判断用户是否在 <input> 中输入了无效数字?或者只是留空?

我尝试使用 valueAsNumber属性,但它是 NaN在这两种情况下。

function showInputValue() {
const inputValue = document.getElementById("numberInput").value;
const inputValueAsNumber = document.getElementById("numberInput").valueAsNumber;

console.log(`value is: "${inputValue}"\nvalueAsNumber is: "${inputValueAsNumber}"`);
}

document.getElementById("btn").addEventListener("click", showInputValue)
<input type="number" id="numberInput" placeholder="try entering text"/>
<button id="btn">Show value</button>

最佳答案

您的输入元素具有实现 ValidityStatevalidity 属性接口(interface):

ValidityState {
badInput: true,
customError: false,
patternMismatch: false,
rangeOverflow: false,
rangeUnderflow: false,
stepMismatch: false,
tooLong: false,
tooShort: false,
typeMismatch: false,
valid: false,
valueMissing: false
}

从这里您可以研究所有有效性状态(valueMissingbadInput 等...)

您可以使用 document.querySelector 获取对您的输入的引用。

在您的情况下,空输入将设置 valueMissing 标志,“1.2.3”输入将设置 badInput 标志。

关于javascript - 我如何判断 &lt;input type=number> 是空白还是具有无效值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52872503/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com