[英]Tel field validation in html to allow digits and text but not @
This code is only digit allowed – Preference should be to allow to enter dash and/or brackets even text such as ext. 该代码仅允许使用数字-优先选择允许输入破折号和/或方括号,例如ext等文本。 but not an email address. 但不是电子邮件地址。
Can you please help me to edit this code? 您能帮我编辑此代码吗? Very appreciated. 非常感激。
<input type="text" maxlength="40" onkeypress="return event.charCode >= 48 && event.charCode <= 57" required name="phone" id="phonecontactselection">
You need a function to check only for @
character to avoid it, so: 您需要一个仅检查@
字符的函数来避免它,因此:
function avoidEmailPartCharacter(event) {
const code = event.keyCode || event.which;
if (code === 64) {
event.preventDefault();
}
}
then you pass the function to the input keypress
handler, like so: 然后将函数传递给输入keypress
处理程序,如下所示:
<input type="type" keypress={avoidEmailPartCharacter(this)} />
it should do the trick 它应该可以解决问题
It's preferable to move such kind of logic of out template, into a dedicated function, however, in case you really have to make it inline , it's possible to match input character against a regex as follows: 最好将这种out模板逻辑移到专用函数中,但是, 如果确实需要使其内联 ,则可以按如下所示将输入字符与正则表达式进行匹配:
<input type="text" maxLength="40" onkeypress="return !!String.fromCharCode(event.which || event.charCode).match(/[\\dext\\[\\]\\-]/)" required name="phone" id="phonecontactselection" >
You could use test and a character class and list your characters that you would allow to match. 您可以使用test和一个字符类,并列出允许匹配的字符。
In this case match one of [
, ]
, a character az
, dot or a hyphen: 在这种情况下,请匹配[
, ]
,字符az
,点或连字符之一:
[\][a-z.-]
<input type="text" maxlength="40" onkeypress="return /[\\][az.-]/.test(String.fromCharCode(event.which || event.keyCode));" required name="phone" id="phonecontactselection" >
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.