[英]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.
但是,使用下面的格式,它确实限制了一个人输入 10 个字符,但它也允许添加任何其他字符。
Now if I change type
to type="number"
maxLength will not work and also characters such as [minus(-) or plus(+)] will still go through.现在,如果我将
type
更改为type="number"
maxLength 将不起作用,并且 [minus(-) 或 plus(+)] 等字符仍将通过 go。
How can I make my input to be only limited to a maximum of 10 numbers and don't allow any characters?如何使我的输入仅限于最多 10 个数字并且不允许任何字符?
<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
}
})
}
/>
You could use regular expression and keyup
event to prevent symbol from typing.您可以使用正则表达式和
keyup
事件来防止输入符号。
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" />
You can use regex
to test your input before setting the state, as:在设置 state 之前,您可以使用
regex
来测试您的输入,如下所示:
<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
}
})
}
}}
/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.