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?

Try This

  <TextField  type="number" 
     label="Short stop treshold"
     InputProps={{
        inputProps: { min: 0 }
      }}
     value={10}
     onChange={handleShortStopChange} />

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

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

If someone else came across it, this solution worked for me:

onKeyPress: event => {
  if(isNumberWithoutSigns && (event?.key === '-' || event?.key === '+')) {
    event.preventDefault();
  }
}

My way using HTML pattern.

  • Allows only number.
  • Shows number pad on mobile.
  • Prevent pasting of
    non-numbers.
  • Show error message if less than 1

code sand box

Read More:   Assign multiple variables to the same value in Javascript?

add pattern props to inputProps to allow only 0 to 9.

pattern: "[0-9]*"

use e.target.validity.valid to check if pattern is valid (only allow 0-9)

 const [ value, setValue ] = useState(1)
    const onChange = (e) => {
          console.log('e.validity', e.target.validity.valid);
          if (e.target.validity.valid || e.target.value === '') setValue(e.target.value)
    }

add type=”tel” (this will show number pad on mobile)

 <TextField
        variant="standard"
        name="price"
        value={value}
        fullWidth
        onChange={onChange}
        type="tel"
        error={value < 1}
        helperText={ value < 1 ? 'Min. 1' : '' }
        inputProps={{
            pattern: "[0-9]*",
        }}
    />

Finally following code worked for me, after combining few answers from other answers in this question.

This works for me with MUI in React Js.

<TextField
  type="number"
  InputProps={{
    inputProps: { min: 0 }
  }}
  onKeyPress={(event) => {
    if (event?.key === '-' || event?.key === '+') {
      event.preventDefault();
    }
  }}
/> 

Might also try use “validator” props in TextField to restrict user to only input positive number.

<TextField
     validator: {(input) => {/*write your function here to check number input greater than 0*/}}
/>

You can use parseInt while setting the value in a state variable.

<TextField
  fullWidth
  type="number"
  placeholder={'[1-100]'}
  id="simple-start-adornmhent"
  onChange={e=>setField(parseInt(e.target.value))}
  InputProps={{ inputProps: { min: 1, max:100 } }}
/>

Textfield in material ui using Hooks only maxlength 10 for mobile numbers NO text and Specialcaes

     const [values1, setValues1] = useState("");
     const handleChange = (e) => {
        
        const re = /^[0-9\b]+$/;
       if (e.target.value === '' || re.test(e.target.value)) {
          setValues1(e.target.value)
       }
    
      };       
    
    return(
     <TextField 
            label="Enter Mobile Number" name="mobile" 
            inputProps={{ maxLength: 10}} value={values1} type="text" 
            onChange={handleChange} className={classes.textfield} />
)

This should work,

inputProps={{min:0}}

This Works

<TextField
  fullWidth
  type="number"
  placeholder={'[1-100]'}
  id="simple-start-adornmhent"
  onChange={this.handleChangeField('amount')}
  InputProps={{ inputProps: { 
   min: 1,
   type: "text",
   pattern: "[0-9]*" 

} }}
/>


The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Similar Posts