如果用户键入无效值(例如:"1.2.3")到<input type=number>,然后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)Run Code Online (Sandbox Code Playgroud)
<input type="number" id="numberInput" placeholder="try entering text"/>
<button id="btn">Show value</button>Run Code Online (Sandbox Code Playgroud)
您的输入元素具有validity实现ValidityState接口的属性:
ValidityState {
badInput: true,
customError: false,
patternMismatch: false,
rangeOverflow: false,
rangeUnderflow: false,
stepMismatch: false,
tooLong: false,
tooShort: false,
typeMismatch: false,
valid: false,
valueMissing: false
}
Run Code Online (Sandbox Code Playgroud)
从这里你可以学习所有的有效性状态(valueMissing,badInput,等...)
您可以使用 获得对输入的引用document.querySelector。
在您的情况下,空输入将设置valueMissing标志,“1.2.3”输入将设置badInput标志。
| 归档时间: |
|
| 查看次数: |
192 次 |
| 最近记录: |