4

I want to use material-UI TextInput to enter only integer values (not decimal values). I used the TextInput as follows, but it still allows the decimal number.

How can I do that?

<TextField id="outlined-value" 
           type="number"
           label="Value" 
           className={classes.standartInputMargin}
           value={this.state.allowedValue}
           margin="normal" 
           variant="outlined"
           onChange={(event) => Number.isInteger(event.target.value) 
               ? this.setState({ allowedValue: event.target.value }) 
               : null} />
1
  • 1
    use converted value in setState Commented Sep 26, 2018 at 12:09

3 Answers 3

3

You're passing the raw value to setState, rather than the integer value. Since your input only accepts numbers, you can just check for decimal places.

onChange = (e) => {
  const { value } = e.target;

  if (value.match('.')) { 
    this.setState({ value: parseInt(value) })
  } 

  return null;
}

Alternatively, if you just have a regular input, something like this would only allow you to enter integers.

onChange = e => {
  const { value } = e.target;
  const parsedInt = parseInt(value);

  if (parsedInt) {
    this.setState({ value: parsedInt });
  }

  return null;
};
Sign up to request clarification or add additional context in comments.

3 Comments

This will reject an input of 0, which may not be what you want. You can use Number.isFinite(parsedInt) instead.
@AndreaReina are you sure? Can't seem to replicate here: codesandbox.io/s/l20v65z129
It accepts an initial value of 0 because that doesn't go through the change handler. Try setting it to another number then back to 0.
1
const setValueHandler = (e) => {
    setValue(e.target.value.replace(/[^0-9]/g, ''));
  }

1 Comment

Need to remove type="Number" from TextField for this.
0

Easiest way i think is to parse value in onChange method.

const NON_DIGIT = '/[^\d]/g';
...
onChange(event) {
    const { value } = event.target;
    const intValue = parseInt(value.toString().replace(NON_DIGIT, ''));

    this.setState({ value: intValue });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.