admin管理员组

文章数量:1321436

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

   @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.

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

   @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.

Share Improve this question edited Feb 15, 2015 at 7:16 Alan Moore 75.3k13 gold badges107 silver badges161 bronze badges asked Feb 13, 2015 at 12:54 Md AslamMd Aslam 1,4168 gold badges36 silver badges69 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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, ' '))
}

Demo

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..)

A better solution could be to 'clean' the input value let's say 500 ms after user stop typing.

var timeout = null;

function CPOnlyAlphaNumeric(evt) {
    if(timeout)
        clearTimeout(timeout);

    timeout = setTimeout(function(){ 
        $(evt).val($(evt).val().replace(/[^A-Za-z0-9]/g, ' '))
    }, 500);
}

Demo

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).

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;
        }
    }

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.

    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;
    }

本文标签: javascriptAllow arrow keys in Regular ExpressionStack Overflow