简体   繁体   中英

How do I make Mui textfield type number only accept number ? Currently it accept numbers,"e" and dashes?

This is my current code.

 <TextField error={values[1].error} fullWidth id="id" type="number" value={values[1].Id} placeholder='Enter ID' onChange={handleChange(1,'Id')} variant="outlined" inputProps={{min: 0,inputMode: 'numeric', pattern: '[0-9]'}} onBlur={() => handleOnBlurEvent(1,'Id')} />

As mentioned by jonrsharpe , numbers containing - or e are still valid numbers.

If you still want to limit the changes that are being accepted, you can make use of a custom handleNumberChange function that filters chars such as e , E and - .

const handleNumberChange = (id: number, key: string, value: string) => {
  if (["e", "E", "-"].some((char) => value.includes(char))) return;

  // handle change here
};

You would use it like that in your MUI <TextField/> :

<TextField
  ...
  onChange={(e) => handleNumberChange(1, "Id", e.target.value)}
/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM