32

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?

2
  • 1
    If you use input with type="number" instead of TextField it should work. Do you need TextField? Commented Jul 30, 2019 at 10:11
  • I recommend looking at the 3rd party integration portion of the documentation. You may also find my answer here helpful. Commented Jul 30, 2019 at 15:05

13 Answers 13

13

Try This

  <TextField  type="number" 
     label="Short stop treshold"
     InputProps={{
        inputProps: { min: 0 }
      }}
     value={10}
     onChange={handleShortStopChange} />
Sign up to request clarification or add additional context in comments.

7 Comments

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: <Autocomplete freeSolo options={defaultNums} onChange={updateNewNum} renderInput={(params) => ( <TextField {...params} label="Amount" type="number" inputProps={{ ...params.inputProps, min: 0, max: 999 }} onChange={updateNewNum} /> )} sx={{ width: '10em' }} />
@takanuva15 how we can get the index of the selected row please to update the data array ?
@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); };
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...
@SidouMahmoud Sorry I don't think I can be of any help there. It sounds like you are talking about an entirely different component.
|
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
    }
/>

Comments

6

This should work,

inputProps={{min:0}}

1 Comment

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.
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

Comments

4

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();
    }
  }}
/> 

Comments

2

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

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

1 Comment

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)
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]*",
        }}
    />

Comments

1

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

Comments

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

Comments

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

Comments

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

Comments

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]*" 

} }}
/>

Comments

-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.

1 Comment

It doesn't work very well, it gives me several problems: codesandbox.io/s/heuristic-sea-u0ey4

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.