如何在JavaScript中使用type=number输入框仅输入0-9(禁止输入'e')
Got it, let's fix this! The default type="number" input supports scientific notation, which is why characters like 'e' (and '+'/'-') are allowed. But since you're using Formik's <Field> with Material-UI's TextField, here are two reliable approaches to lock input down to just 0-9 digits:
Approach 1: Block Forbidden Keys on Keypress
First, we can intercept keyboard events to prevent 'e', 'E', '+' and '-' from being entered at all. Create a handler function:
const handleNumberKeyDown = (e) => { // List of characters we want to block const forbiddenChars = ['e', 'E', '+', '-']; if (forbiddenChars.includes(e.key)) { e.preventDefault(); // Stop the character from being typed } };
Then pass this handler to your <Field> via inputProps (since TextField accepts input props through this prop):
<Field name="weight" type="number" component={TextField} placeholder="" label="Weight(%)" width={250} inputProps={{ onKeyDown: handleNumberKeyDown, // Optional: Add min/max to enforce percentage range min: 0, max: 100 }} />
Approach 2: Filter Input (Including Paste Events)
The keydown handler won't catch pasted content that includes 'e', so add an onInput handler to clean up the input value after any change:
const handleNumberInput = (e) => { // Replace any non-digit characters with an empty string e.target.value = e.target.value.replace(/[^0-9]/g, ''); };
Update your <Field> to include both handlers for full coverage:
<Field name="weight" type="number" component={TextField} placeholder="" label="Weight(%)" width={250} inputProps={{ onKeyDown: handleNumberKeyDown, onInput: handleNumberInput, min: 0, max: 100 }} />
Why This Works
- The
onKeyDownhandler stops forbidden characters from being typed directly. - The
onInputhandler cleans up any invalid content that might get pasted into the field. - We keep
type="number"so you retain native number input features like arrow controls and mobile number keyboards.
If you wanted to go a different route, you could switch to type="text" with a pattern="[0-9]*" prop, but that loses the native number input behaviors—so the above methods are usually the better tradeoff.
内容的提问来源于stack exchange,提问作者ppppp

