Limit the number of input characters for React App input form fields of type number, tel. The input form fields have an HTML attribute called maxlength that is used to limit the number of characters input by the user.
But the problem with maxlength is that it is only applicable for input type text. It shows error when used with input type=”number” or type =”tel”.
So we may encounter situations when we have to limit the number of input numbers. For example input field that takes the mobile number as of the use. We may need only 10 digits for an example case. We may need to limit the user input to only 10 digits.
We can make use of the below code for that.
maxLength for input number React JS – example code
export default function Form() { const [phoneNumber, setPhoneNumber] = useState(""); //state to store phone num return <div> <label> Phone Number </label> <input type="tel" name="phone" value={phoneNumber} onChange={(event) => { if(event.target.value.length==11) return false; //limits to 10 digit entry setPhoneNumber(event?.target.value); //saving input to state } } id="tel" placeholder="Your phone no (10 digit)" /> </div> }
Using the above code we can easily implement phone / mobile number input length limit in our React Javascript applications.