i tried this to restrict user from entering more than 10 numbers
numberChangeHandler=(e)=>{
const userInput={...this.state.userInput};
if(userInput.number.length>=10)
{
e.preventDefault();
}
else{
userInput[e.currentTarget.name]=e.currentTarget.value
}
this.setState({userInput})
}
but i wont be able to alter any changes once it reaches 10 digits .. cant use backspace as well. Then i tried this:
numberChangeHandler=(e)=>{
const userInput={...this.state.userInput};
if(userInput.number.length>10)
{
userInput[e.currentTarget.name]=e.currentTarget.value.replace("")
}
else{
userInput[e.currentTarget.name]=e.currentTarget.value
}
this.setState({userInput})
}
but this replaces my complete userInput to empty string once it reached 10 digits. can i get a solution please
CodePudding user response:
This is how you get the number length
var x = 1234567;
x.toString().length;
Then if the variable is less than 10 you update the state, if its not you simply do nothing.
if(this.state.userInput.toString().length < 10 ){
this.setState({
userInput: "The New User Input"
})
}
CodePudding user response:
Actually you don't have to handle the number of characters yourself, input
does provides you an attribute to do that.
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/text
<input type="text" id="name" name="name" required
minlength="4" maxlength="8" size="10">
From the code sample above you can enter anything between 4 to 8, however do take note that because you are using reactJS
, change the casing like maxLength
instead
CodePudding user response:
numberChangeHandler=(e)=>{
const userInput={...this.state.userInput};
if(userInput.number.length>=10)
{
userInput[e.currentTarget.name]=e.currentTarget.value
userInput.number=userInput.number.substr(0,10)
}
else{
userInput[e.currentTarget.name]=e.currentTarget.value
}
this.setState({userInput})
}