only allowing numbers upto certain length in material ui

Viewed 6356

We need user to enter only numbers and it should have a maximum length of say 3. How can we accomplish this in material ui ?

<TextField
  id="score"
  label="score"
  className={classes.textField}
  name="totalScore"
  margin="normal"
  defaultValue={score}
/>

We want only numeric values here

6 Answers

Try this...

<TextField
  id="score"
  label="score"
  name="totalScore"
  style={style.filedStyle}
  inputProps={{ min: 3, max: 3}}
/>

Actually this is the way it works, you have input type as number. so, you can apply max attribute but it will validate not limit the input numbers, Checkout this thread.

The workaround is to apply oninput and count the length. like this

 onInput={(e)=>{ 
        e.target.value = Math.max(0, parseInt(e.target.value) ).toString().slice(0,3)

So your textinput would look like

<TextField type="number"
    className="text-field-amount"
    onInput={(e)=>{ 
        e.target.value = Math.max(0, parseInt(e.target.value) ).toString().slice(0,2)
    }}
    min={0}
/>

Demo

<TextField
  id="score"
  label="score"
  className={classes.textField}
  name="totalScore"
  margin="normal"
  defaultValue={score}
/>

you can do this with Jquery

$('#score').keypress(function(e){
    var code = (e.which) ? e.which : e.keyCode;
    if($('#' + e.target.id).val().length > 2)
        e.preventDefault();
    if (code > 31 && (code < 48 || code > 57)) {
        e.preventDefault();
    }
});

Use controlled input, and update state only if the input is number.

ex: state will be like this

this.state={
    score: 0
}

create a function to handle change in text field.

handleChange(e){
    //update state here with value from TextField.
}

and your textfield will look like this.

<TextField
  id="score"
  label="score"
  className={classes.textField}
  name="totalScore"
  margin="normal"
  value={this.state.score}
  onChange={this.handleChange.bind(this)}
/>
             <TextField
              id="number"
              placeholder="Enter Number"
              type="number"
              value={state.count}
              onChange={(event) => {
                const regex = /^([0-9]){minLength,maxLength}$/;
                if (event.target.value === '' || regex.test(event.target.value)) {
                  setState({ ...state, count: event.target.value });
                }
              }}
              variant="outlined" />

number + length restriction

<TextField
   value={phone}
   onChange={event => setPhone(event.target.value)}
   variant="outlined"
   placeholder={'Phone number'}
   type={'number'}
   onInput={(e)=>{e.target.value = Math.max(0, parseInt(e.target.value)).toString().slice(0,10)}}
   min={0} 
/>
Related