aharrrisssss
aharrrisssss

Reputation: 21

How to prevent user from entering letters into TextField using material ui

I have some TextField where the user can only enter positive digits. Right now I have this onKeyDown:

<TextField
        label={distanceError}
        error={!!distanceError}
        defaultValue={kpoints.distance}
        onBlur={handleDistanceChange}
        **onKeyDown={(evt) =>
          ['+', '-'].includes(evt.key) && evt.preventDefault()
        }**
        InputLabelProps={{
          shrink: true,
        }}
        inputProps={{
          min: 0,
          id: 'distance-input',
          style: {textAlign: 'center'},
        }}
        variant="outlined"
        size="small"
        type="number"
        aria-label="Distance in angstroms input"
      ></TextField>

This prevents any special characters because I do not want the user to be able to enter negative numbers.

What can I add to this to prevent the user from entering letters a-z?

Also I need to prevent it turning the number into a string once the user enters a different number.

Please help!

Upvotes: 2

Views: 3638

Answers (2)

Lascaux Lascaux
Lascaux Lascaux

Reputation: 51

Or you could use this. Since other uses the AirBnB guide which they could get an error in eslint when using only isNaN.

<TextField
  value={value}
  variant="outlined"
  onChange={(event) => {
    setValue(!Number.isNaN(Number(event.target.value)) ? event.target.value : value);
  }}
  size="small"
/>

Upvotes: 2

Ralph
Ralph

Reputation: 35

Inputs from a TextField (or input) always considered string. You can check if the value is NaN with a helper function:

const check = (input) => {
  if (isNaN(input)) {
    return false;
  } else {
    return Number(input);
  }
};

If value is a string that isn't convertible to a number it returns false, otherwide it returns an integer value you can set as your new state.

Update: try this:

<TextField
  value={value}
  variant="outlined"
  onChange={(event) => {
    setValue(!isNaN(event.target.value) ? event.target.value : "");
  }}
  size="small"
/>

Upvotes: 0

Related Questions