Reputation: 103
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
Upvotes: 3
Views: 8383
Reputation: 74
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}
/>
Upvotes: 0
Reputation: 61
<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" />
Upvotes: 0
Reputation:
<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();
}
});
Upvotes: 0
Reputation: 123
Try this...
<TextField
id="score"
label="score"
name="totalScore"
style={style.filedStyle}
inputProps={{ min: 3, max: 3}}
/>
Upvotes: 7
Reputation: 13801
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}
/>
Upvotes: 3
Reputation: 464
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)}
/>
Upvotes: 0