1. I want to limit the input type text field length to 6 (which means allow numbers only from 0 to 999999 range).
2. Even if it is of type number it allows entry of E, e, -, + . How to prevent this too.
I have tried setting the min=0, max=999999 and maxlength=6 etc but none of them worked for me. Given bellow my input field code in react.
<TextField
id="sampleFiled"
label="VCode"
type="number"
required
className="text-field"
value={this.state.code}
margin="normal"
/>
Use the maxLength prop to set a character limit on an input field in React, e.g. <input maxLength={5} /> . The maxLength attribute defines the maximum number of characters the user can enter into an input field or a textarea element.
To prevent e and dot in an input type number with React, we can validate the input value in the onChange prop function. const C = () => { //... const [val, setVal] = useState(""); return ( <div className="App"> <input type="text" value={val} onChange={(e) => setVal(e. target.
To only allow numbers to be entered in an input in React, we can set the pattern attribute of the input to only allow digits to be inputted. Then in the onChange handler, we only set the value of the input when the inputted value is valid.
insert the following function in input type="number"
<input type = "number" maxLength = "5" onInput={this.maxLengthCheck} />
React function
maxLengthCheck = (object) => {
if (object.target.value.length > object.target.maxLength) {
object.target.value = object.target.value.slice(0, object.target.maxLength)
}
}
isNaN()
and Number
can be combined to reject strings
that don't evaluate to numbers
.
See below for a practical example.
// Field.
class Field extends React.Component {
// State.
state = { value: '' }
// Render.
render = () => <input placeholder="Numbers only" value={this.state.value} onChange={this.handlechange}/>
// Handle Change.
handlechange = ({target: {value}}) => this.setState(state => value.length <= 6 && !isNaN(Number(value)) && {value} || state)
}
// Mount.
ReactDOM.render(<Field/>, document.querySelector('#root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With