29

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?

Ninjakannon
  • 3,751
  • 7
  • 53
  • 76
Paul
  • 3,644
  • 9
  • 47
  • 113
  • 1
    If you use input with type="number" instead of TextField it should work. Do you need TextField? – VoidChips Jul 30 '19 at 10:11
  • I recommend looking at the [3rd party integration portion](https://material-ui.com/components/text-fields/#integration-with-3rd-party-input-libraries) of the documentation. You may also find my answer [here](https://stackoverflow.com/questions/53981996/how-can-i-set-material-ui-textfield-to-accept-only-hexidecimal-characters/53989369#53989369) helpful. – Ryan Cogswell Jul 30 '19 at 15:05

13 Answers13

9

Try This

  <TextField  type="number" 
     label="Short stop treshold"
     InputProps={{
        inputProps: { min: 0 }
      }}
     value={10}
     onChange={handleShortStopChange} />
Haroun Darjaj
  • 274
  • 1
  • 6
Shahnad S
  • 983
  • 10
  • 17
  • Based on their documentation, I did this instead which prevented the css from getting messed up: `inputProps={{ ...params.inputProps, min: 0, max: 999 }}`. Full element: ` ( )} sx={{ width: '10em' }} />` – takanuva15 Apr 26 '22 at 03:00
  • @takanuva15 how we can get the index of the selected row please to update the data array ? – Sido4odus Apr 29 '22 at 20:46
  • @SidouMahmoud I'm confused what you mean by "selected row"? Are you referring to which option was picked in the Autocomplete? If so, you can access `e.target.dataset.optionIndex` in the onChange fn like so: `const onChangeFunc = (e: React.SyntheticEvent, newValue: string | number | null) => { console.log("selected row index is: ", e.target.dataset.optionIndex); };` – takanuva15 May 01 '22 at 13:59
  • I was refering to the row we are aiming to update, I found a solution with the `editable` parameter and `onRowUpdate` function, still try to make the same functionality with custom component (custom row). If you know how to define the same function `onRowUpdate` on a custom component please tell me... – Sido4odus May 02 '22 at 09:49
  • @SidouMahmoud Sorry I don't think I can be of any help there. It sounds like you are talking about an entirely different component. – takanuva15 May 03 '22 at 20:18
  • yeah, I mean I want to fire `rowUpdate` event in a custom row (defined in a seperate component) – Sido4odus May 04 '22 at 06:47
  • this does not let changing on its arrows to negative but you can still enter negative value manually. so it also needs the custom on change implementation – Aras Dec 27 '22 at 16:35
7

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
    }
/>
Pitter
  • 498
  • 7
  • 15
4

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

4

This should work,

inputProps={{min:0}}
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 01 '22 at 13:21
3

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();
    }
  }}
/> 
Kamal Panara
  • 482
  • 7
  • 16
2

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

onKeyPress: event => {
  if(isNumberWithoutSigns && (event?.key === '-' || event?.key === '+')) {
    event.preventDefault();
  }
}
  • I got errors when I put the question mark in - so I'm not sure what's happening there. However, this is a great solution! If you want to disallow decimals, just add a check for '.' as well, and remember that many browsers allow 'e' as a number. That starts getting to be a long conditional - I did this: ['-','+','e','.'].includes(event.key) – Michael Jay Feb 14 '22 at 18:57
1

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

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]*",
        }}
    />
Someone Special
  • 12,479
  • 7
  • 45
  • 76
0

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*/}}
/>
Ivy
  • 17
  • 1
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 } }}
/>
Shrey Tiwari
  • 169
  • 1
  • 6
0

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} />
)
soma iyappan
  • 482
  • 7
  • 16
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]*" 

} }}
/>
Munei Nengwenani
  • 113
  • 2
  • 10
0

I hope what I'm proposing works for you or any other person that may still need it. I used a regex in the onInput prop, in conjunction with the InputProps.inputProps.min value. It works for me in MUI v5.

<TextField
    type="number"
    size="small"
    variant="standard"
    onInput={(e: any) => {
        const target = e.target;
        target.value = e.target.value.replace(/[^0-9]/g, "");
    }}
    InputProps={{
        inputProps: {
            min: 0,
        },
    }}
/>
Wisdom
  • 1
  • 1
-1

By using Regex you can remove non-numaric characters. Check This snippet:

onChanged (text) {
    this.setState({
        YourAmountVariable: text.replace(/[^0-9]/g, ''),
    });
}

this will remove any non numeric character from your input.

Najam Us Saqib
  • 3,190
  • 1
  • 24
  • 43
  • 1
    It doesn't work very well, it gives me several problems: https://codesandbox.io/s/heuristic-sea-u0ey4 – Paul Jul 30 '19 at 10:56