【发布时间】:2022-01-15 18:58:57
【问题描述】:
我正在尝试使用 replace() 函数验证电话号码模式。如果数字的第一个数字不是以 3 开头,并且数字长度不得超过总 10 位数字,我需要删除该数字的第一个数字,并在用户键入时删除长度为 10 后的其他输入数字。
这是我的代码:
function phoneNumber(element){
if(element.value.length != 0){
element.value = element.value.replace(/^0[^0-9].{9}/, '');
}
}
<input type="text" name="phone" required oninput="phoneNumber(this)"/>
我想要的是,如果用户键入除 3 之外的第一个数字,那么该数字将被删除,并且该数字的总长度将为 10。 一些需要理解的案例:
3430215478 // acceptable
343454545454 // not acceptable and replace() should remove the last two digits 54
0347878788 // not acceptable and replace() should remove the first digit 0
+924544444 // not acceptable and replace() should remove the all the digits because it does not start with 3
我尝试了在 Internet 上找到的不同正则表达式,但在 replace() 函数中不起作用。 如果您能帮助我,我将不胜感激。
【问题讨论】:
-
希望这篇文章对您有所帮助: stackoverflow.com/questions/8358084/…
标签: javascript html regex