最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin3浏览0评论

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')} />
                   

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')} />
                   

Share Improve this question asked Aug 4, 2022 at 8:07 tosseftossef 111 gold badge1 silver badge2 bronze badges 3
  • 2 E.g. -1e2 is a valid number. – jonrsharpe Commented Aug 4, 2022 at 8:12
  • thats becoz e is for exponential, if you want to restrict it then probably you need to have a custom validation using keyup or keydown – Amaarockz Commented Aug 4, 2022 at 8:12
  • can you please suggest any documentation to restrict e and dashes? – tossef Commented Aug 4, 2022 at 8:21
Add a ment  | 

1 Answer 1

Reset to default 2

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)}
/>

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论