Home > Enterprise >  How to restrict numbers (even in String type) from MaterialUI TextField?
How to restrict numbers (even in String type) from MaterialUI TextField?

Time:01-10

Consider the following code:

<Grid item lg={6} md={6} xs={12} >
     <TextField fullWidth type={'text'} label="Product Color" value={productColor} onChange={(e) => setProductColor(e.target.value)} />
</Grid>

Even if it is set to type text, how do I completely prevent numbers from being entered and only allow text from A-z or a-z? Any Ideas?

CodePudding user response:

One way would be to to utilise the fact that you can pass in certain props to text fields and combine this with regex. This wouldn't necessarily prevent them from allowing it to be entered, however, it will prevent submission of the text field if it contains any numbers. You would then just need to add error handling to display the associated message

<TextField
  inputProps={{ pattern: "([^0-9]*)" }} error={'Error Message'}
/>

Check out the textfield api Preview of a TextField input only accepting prices with 2 digits behind the comma

  •  Tags:  
  • Related