I am performing alphanumeric validation and now I am doing that user can only enter an alphanumeric value and also allow alphanumeric values only while pasting. So I used the following regular expression
我正在执行字母数字验证,现在我正在做的用户只能输入字母数字值,并且仅在粘贴时允许使用字母数字值。所以我使用了以下正则表达式
function OnlyAlphaNumeric(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode;
if ((charCode > 32 && charCode < 48) || (charCode > 57 && charCode < 65) ||
(charCode > 90 && charCode < 97) || charCode > 122) {
return false;
}
else {
return true;
}
}
And for preventing the copy and paste,
并且为了防止复制和粘贴,
function CPOnlyAlphaNumeric(evt) {
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}
These two functions are calling from the following onkeypress and onkeyup methods such that is given below as shown that
这两个函数是通过以下onkeypress和onkeyup方法调用的,如下所示,如下所示
@Html.TextBoxFor(model => model.ProductName, new { @class = "form-
control", @onkeypress = "return OnlyAlphaNumeric(this);", @onkeyup=
"return CPOnlyAlphaNumeric(this);" })
This works for alphanumeric validation, but it doesn't allow the cursor to move left side for editing the text. So what will change I should do in my Regular Expression.
这适用于字母数字验证,但它不允许光标向左移动以编辑文本。那么我将在正则表达式中做些什么会改变。
3 个解决方案
#1
3
Your problem has nothing related to regular expressions.
您的问题与正则表达式无关。
When you press any key (including left/right arrow) you take value of input, replace all forbidden characters and set the value of the input. When last action is done it's the browser native behavior to move the cursor to the end of input.
当您按任意键(包括左/右箭头)时,您将获取输入值,替换所有禁用的字符并设置输入值。当最后一个操作完成时,浏览器本机行为将光标移动到输入的末尾。
You can check what is the pressed key and if it's left/right arrow to skip the manipulation of input value.
您可以检查按下的键是什么,如果是左/右箭头则跳过输入值的操作。
function CPOnlyAlphaNumeric(evt) {
var code = evt.which ? evt.which : event.keyCode;
// 37 = left arrow, 39 = right arrow.
if(code !== 37 && code !== 39)
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}
演示
However this is not a good solution because it will result in a terrible behavior (you won't be able to use shift for mark, the cursor will be moved at the end after first typed letter in the middle of word etc..)
然而,这不是一个好的解决方案,因为它会导致一个糟糕的行为(你将无法使用shift作为标记,光标将在单词等中间的第一个输入字母后的末尾移动。)
A better solution could be to 'clean' the input value let's say 500 ms after user stop typing.
一个更好的解决方案可能是“清理”输入值,比如用户停止输入后500毫秒。
var timeout = null;
function CPOnlyAlphaNumeric(evt) {
if(timeout)
clearTimeout(timeout);
timeout = setTimeout(function(){
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}, 500);
}
演示
Please note that you need to add the validation on server side as well (and maybe before the form submit, because user can hit enter to submit the form before the 'cleaning' of input is triggered).
请注意,您还需要在服务器端添加验证(可能在表单提交之前,因为用户可以在触发输入'清理'之前按Enter键提交表单)。
#2
2
You can try this, it may solve your problem.
你可以尝试这个,它可以解决你的问题。
var regex = new RegExp("^[a-zA-Z0-9]+$");
var charCode =(typeof event.which == "number") ?event.which:event.keyCode
var key = String.fromCharCode(charCode);
if (!(charCode == 8 || charCode == 0)) {
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
#3
1
Problem with keyDown event is that you cant suppress the display of keys in the textfield (only alpha numeric in my case). You can do it in only keyPress event. But you cant get navigation keys in keyPress event, you can only track them in KeyDown event. And some of the keys $,%, have the same e.which that arrow keys has in keypress event. which is causing issues for me to write the logic to allow arrow keys but restrict the text to only Alpha numeric. Here is the code I came up with. Working fine now.
keyDown事件的问题是您无法抑制文本字段中键的显示(在我的情况下只有字母数字)。您只能在keyPress事件中执行此操作。但是你无法在keyPress事件中获得导航键,你只能在KeyDown事件中跟踪它们。并且一些键$,%具有与按键事件中箭头键相同的e.which。这导致我编写逻辑以允许箭头键但将文本限制为仅Alpha数字的问题。这是我想出的代码。现在工作正常。
onKeyPress: function(e){
var regex = new RegExp("^[a-zA-Z0-9\b ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
var allowedSpecialKeys = 'ArrowLeftArrowRightArrowUpArrowDownDelete';
var key = e.key;
/*IE doesn't fire events for arrow keys, Firefox does*/
if(allowedSpecialKeys.indexOf(key)>-1){
return true;
}
if (regex.test(str)) {
return true;
}
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
return false;
}
#1
3
Your problem has nothing related to regular expressions.
您的问题与正则表达式无关。
When you press any key (including left/right arrow) you take value of input, replace all forbidden characters and set the value of the input. When last action is done it's the browser native behavior to move the cursor to the end of input.
当您按任意键(包括左/右箭头)时,您将获取输入值,替换所有禁用的字符并设置输入值。当最后一个操作完成时,浏览器本机行为将光标移动到输入的末尾。
You can check what is the pressed key and if it's left/right arrow to skip the manipulation of input value.
您可以检查按下的键是什么,如果是左/右箭头则跳过输入值的操作。
function CPOnlyAlphaNumeric(evt) {
var code = evt.which ? evt.which : event.keyCode;
// 37 = left arrow, 39 = right arrow.
if(code !== 37 && code !== 39)
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}
演示
However this is not a good solution because it will result in a terrible behavior (you won't be able to use shift for mark, the cursor will be moved at the end after first typed letter in the middle of word etc..)
然而,这不是一个好的解决方案,因为它会导致一个糟糕的行为(你将无法使用shift作为标记,光标将在单词等中间的第一个输入字母后的末尾移动。)
A better solution could be to 'clean' the input value let's say 500 ms after user stop typing.
一个更好的解决方案可能是“清理”输入值,比如用户停止输入后500毫秒。
var timeout = null;
function CPOnlyAlphaNumeric(evt) {
if(timeout)
clearTimeout(timeout);
timeout = setTimeout(function(){
$(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
}, 500);
}
演示
Please note that you need to add the validation on server side as well (and maybe before the form submit, because user can hit enter to submit the form before the 'cleaning' of input is triggered).
请注意,您还需要在服务器端添加验证(可能在表单提交之前,因为用户可以在触发输入'清理'之前按Enter键提交表单)。
#2
2
You can try this, it may solve your problem.
你可以尝试这个,它可以解决你的问题。
var regex = new RegExp("^[a-zA-Z0-9]+$");
var charCode =(typeof event.which == "number") ?event.which:event.keyCode
var key = String.fromCharCode(charCode);
if (!(charCode == 8 || charCode == 0)) {
if (!regex.test(key)) {
event.preventDefault();
return false;
}
}
#3
1
Problem with keyDown event is that you cant suppress the display of keys in the textfield (only alpha numeric in my case). You can do it in only keyPress event. But you cant get navigation keys in keyPress event, you can only track them in KeyDown event. And some of the keys $,%, have the same e.which that arrow keys has in keypress event. which is causing issues for me to write the logic to allow arrow keys but restrict the text to only Alpha numeric. Here is the code I came up with. Working fine now.
keyDown事件的问题是您无法抑制文本字段中键的显示(在我的情况下只有字母数字)。您只能在keyPress事件中执行此操作。但是你无法在keyPress事件中获得导航键,你只能在KeyDown事件中跟踪它们。并且一些键$,%具有与按键事件中箭头键相同的e.which。这导致我编写逻辑以允许箭头键但将文本限制为仅Alpha数字的问题。这是我想出的代码。现在工作正常。
onKeyPress: function(e){
var regex = new RegExp("^[a-zA-Z0-9\b ]+$");
var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
var allowedSpecialKeys = 'ArrowLeftArrowRightArrowUpArrowDownDelete';
var key = e.key;
/*IE doesn't fire events for arrow keys, Firefox does*/
if(allowedSpecialKeys.indexOf(key)>-1){
return true;
}
if (regex.test(str)) {
return true;
}
e.preventDefault();
e.stopPropagation();
e.cancelBubble = true;
return false;
}