You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中使用type=number输入框仅输入0-9(禁止输入'e')

Restricting Material-UI TextField (type=number) to Only 0-9 Digits (No 'e' Character)

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 onKeyDown handler stops forbidden characters from being typed directly.
  • The onInput handler 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:07:36