Reputation: 21
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
}
})
}
/>
Upvotes: 1
Views: 608
Reputation: 2787
You could use regular expression and keyup
event to prevent symbol from typing .
let input = document.querySelector('input')
input.onkeyup = function() {
input.value = input.value.replace(/[^\d]/, "")
}
<input placeholder="Telephone Number" className="input_fields telephone_no" type="tel" maxLength={ "10"} name="phoneNumber" id="teacher_telephone_no" />
Upvotes: 0
Reputation: 2695
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
}
})
}
}}
/>
Upvotes: 1