作者:阿宅是时候听孙燕姿思_542 | 来源:互联网 | 2023-10-11 20:57
Imtryingtocreatearegextomatchanumberwiththefollowingcriteria:•Length12•Firstchar
I'm trying to create a regex to match a number with the following criteria: • Length 12 • First character must be a 8 • The remaining 11 must be numeric 0-9
我正在尝试创建一个正则表达式以匹配具有以下条件的数字:•长度12•第一个字符必须是8•其余11个必须是数字0-9
This is what I'm trying, but it does not work:
这就是我正在尝试的,但它不起作用:
$(".ValidarTelefono").keypress(function (e) {
tecla = (document.all) ? e.keyCode : e.which;
if (tecla == 8) return true;
patron = /^8\d{12}$/;
te = String.fromCharCode(tecla);
return patron.test(te);
});
Could someone tell me where I went wrong?
有人能告诉我哪里出错了吗?
4 个解决方案
I think what you are looking for is the following:
我认为您正在寻找的是以下内容:
$(".ValidarTelefono").keypress(function (e) {
patron = /^8\d{11}$/;
if (patron.test($(this).val())) {
. . . DO SOMETHING . . .
}
else {
. . . DO SOMETHING ELSE . . .
}
});
What that code should do is check to see if the current value of the field is a 12-digit number that begins with 8, every time a key is pressed in the field.
该代码应该做的是检查字段的当前值是否是每次在字段中按下键时以8开头的12位数字。
You don't want to return the result of the .test()
, since, everytime it fails, it will block the character from being entered into the field.
您不希望返回.test()的结果,因为每次失败时,它都会阻止字符进入字段。
EDIT : It occured to me that you might be trying to block any character that would not result in the creation of a 12-digit character, that begins with 8 . . . that code would be a little different:
编辑:我发现你可能试图阻止任何不会导致创建12位字符的字符,以8开头。 。 。那段代码会有点不同:
First, controle the length of the number from within the text input by adding the maxlength = 12
attribute.
首先,通过添加maxlength = 12属性来控制文本输入中的数字长度。
Then, use the following code to check the characters:
然后,使用以下代码检查字符:
$(".ValidarTelefono").keypress(function (e) {
var tecla = (document.all) ? e.keyCode : e.which;
if (tecla == 8) {
return true;
}
else {
var te = String.fromCharCode(tecla);
if ($(this).val().length === 0) {
return (te === "8");
}
else {
var patron = /\d/;
return patron.test(te);
}
}
});
That being said, there are some BIG problems with this approach. You put a lot of restrictions on what the user can do with their keyboard. They can use Backspace
to delete, but the can't use Delete
. . . the can't use the arrow keys or Home
or End
to change the cursor position, they can't use Ctrl-V
to paste in a valid value, etc.
话虽如此,这种方法存在一些大问题。你对用户的键盘操作有很多限制。他们可以使用Backspace删除,但不能使用Delete。 。 。不能使用箭头键或Home或End来改变光标位置,它们不能用Ctrl-V粘贴有效值等。
I would be VERY hesitant to use this approach.
我会非常犹豫使用这种方法。