Skip to content
Advertisement

How can I make my input to be only limited to a maximum of 10 numbers and don’t allow any characters?

I want to be able to put a maximum length for the phone number entered and don’t allow any characters too. However, with the format below it does limit the person to enter 10 characters but it also allows any other character to be added too.

Now if I change type to type="number" maxLength will not work and also characters such as [minus(-) or plus(+)] will still go through.

How can I make my input to be only limited to a maximum of 10 numbers and don’t allow any characters?

<input
  placeholder="Telephone Number"
  className="input_fields telephone_no"
  type="tel"
  maxLength={"10"}
  name="phoneNumber"
  id="teacher_telephone_no"
  value={this.state.user.phoneNumber}
  onChange={e =>
    this.setState({
      user: {
        ...this.state.user,
        [e.target.name]: e.target.value
      }
    })
  }
/>

Advertisement

Answer

You can use regex to test your input before setting the state, as:

     <input
        placeholder="Telephone Number"
        className="input_fields telephone_no"
        type="tel"
        maxLength={"10"}
        name="phoneNumber"
        id="teacher_telephone_no"
        value={user}
        onChange={(e) => {
          if (/^[0-9]{1,10}$/.test(e.target.value)) {
             this.setState({
               user: {
               ...this.state.user,
               [e.target.name]: e.target.value
               }
            })
          }
        }}
      />
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement