Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS Material-UI: Accept only positive unsigned integer values in TextField

I have the following input field, I would like it to accept only positive integers, without giving the possibility to insert the characters - + , ..

<TextField
  fullWidth
  type="number"
  placeholder={'[1-100]'}
  id="simple-start-adornmhent"
  onChange={this.handleChangeField('amount')}
  InputProps={{ inputProps: { min: 1 } }}
/>

Can you give me some advice?

like image 494
Paul Avatar asked Jul 30 '19 10:07

Paul


People also ask

How do you allow only numbers in input field React?

Basic idea is: Use controlled component (use value and onChange property of input field), and inside onChange handle check whether the entered value is proper number or not. Update the state only when entered value is a valid number.

How do I change the default value in TextField material UI?

The MUI TextField can display a default value on render by using the defaultValue prop. This is useful if you don't need to externally get or set the TextField value, or if you are using a form. A form will automatically extract a TextField child components value on submit of the form.


3 Answers

In the onChange method you can create your own rule to deal with the data.

In this case below, if the input value is less then zero, then I set the value to zero.

This solved my problem. You can improve the rule as you need.

<TextField
    type={"number"}
    onChange={(event) =>
        event.target.value < 0
            ? (event.target.value = 0)
            : event.target.value
    }
/>
like image 119
Pitter Avatar answered Oct 30 '22 23:10

Pitter


How about setting type to "text" and manually control the input? try this:

<TextField
  value={this.state.value}
  onChange={(e) => {
    let input = e.target.value ;
    if( !input || ( input[input.length-1].match('[0-9]') && input[0].match('[1-9]')) )
      this.setState({value:input})
  }}
  type="text"
  placeholder={'[1-100]'}
/>

with this code we only allow the first character to be [1-9] and the following charaters to be [0-9]. we also allow the TextField to be empty

like image 39
Alireza Bagheri Avatar answered Oct 31 '22 00:10

Alireza Bagheri


Try This

  <TextField  type="number" 
     label="Short stop treshold"
     InputProps={{
        inputProps: { min: 0 }
      }}
     value={10}
     onChange={handleShortStopChange} />
like image 7
Shahnad Avatar answered Oct 31 '22 00:10

Shahnad