javascript javascript中的正则表达式允许退格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14473666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
regular expression in javascript which allows backspace
提问by Amith
My regular expression which allows characters, numbers, dot and underscore is
我允许字符、数字、点和下划线的正则表达式是
var numericReg = /^[a-zA-Z0-9\._]+$/;
How could i allow backspace in this reg ex.?
我怎么能在这个 reg ex. 中允许退格?
采纳答案by Amith
The optimal solution for this problem is to check the value of textbox >0 before validating. This will help to solve error showing while pressing backspace in an empty textbox..!!
此问题的最佳解决方案是在验证之前检查 textbox >0 的值。这将有助于解决在空文本框中按退格键时显示的错误..!!
回答by Rohit Jain
You can use [\b]
to match backspace. So, just add it to your character class: -
您可以使用[\b]
来匹配退格键。因此,只需将其添加到您的角色类中:-
var numericReg = /^[a-zA-Z0-9._\b]+$/;
Note that you don't need to escape dot (.)
in character class. It has not special meaning in there.
请注意,您不需要dot (.)
在字符类中转义。它在那里没有特别的意义。
See also: -
也可以看看: -
for more escape sequences, and patterns in Regex.
有关更多转义序列和正则表达式中的模式。
回答by Elvis
Check against 'event.keyCode' and 'value.length' before checking the regular expression.
Keycode 8 = backslash
在检查正则表达式之前检查“event.keyCode”和“value.length”。
键码 8 = 反斜杠
$('#my-input').on('keypress change', function(event) {
// the value length without whitespaces:
var value_length = $(this).val().trim().length;
// check against minimum length and backspace
if (value_length > 1 && event.keyCode != 8) {
var regex = new RegExp('/^[a-zA-Z0-9\._]+$/');
var key = String.fromCharCode(!event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
}
回答by Marvin
I also made a input type text that accept only numbers(non decimal) and backspace keyboard. I notice that putting [\b] in regular expression is not needed in non Firefox browser.
我还制作了一个仅接受数字(非十进制)和退格键盘的输入类型文本。我注意到在非 Firefox 浏览器中不需要将 [\b] 放在正则表达式中。
var regExpr = new RegExp("^[0-9,\b][0-9,\b]*$");
回答by psi-All
I'd suggest you rewrite your regex to :
我建议您将正则表达式重写为:
var numericReg = /^[a-zA-Z0-9._]+|[\b]+$/
Or:
或者:
var numericReg = /^(?:[a-zA-Z0-9._]|[\b])+$/