开发者

Do not allow '&*' pair Textarea in Java Script

While adding text in a textarea, I dont want to allow '*' after '&'.

I want to check on Asterisk keypress, whether previous symbol added is '&', if yes, user cannot add '*'.开发者_运维技巧

Kindly help, how to proceed.


You might be better off having a general function that runs after every "keyup" event which cleans up the textarea by removing any asterisks (*) immediately after an ampersand (&). This way, even if the user pastes some content which contains the invalid sequence (&*) it will still be cleaned up. So something like this:

myTextArea.onkeyup = function() {
  myTextArea.value = myTextArea.value.replace(/&\*/, '&');
  return true;
};


    var input = document.getElementById("input");
    input.addEventListener("keydown", function(e) {
        if(e.shiftKey && e.keyCode === 55 && input.value.substr(input.value.length - 1) === "*") {
            e.preventDefault();
        }
    },false);

This will add an event to check the incoming character and the last in the current input. If the incoming is shift+55 (thats shift-7 or &) and the last character in the input is "*" preventDefault will bail out of the event and not input what was just typed. This example wont work in IE because its using addEventListener but the same approach will work with IE attachEvent or event jQuery events for full cross browser.


Because you can paste using contextual menu, Ctrl-V, Shift-Ins, etc...

myTextArea.onchange = function() {
  myTextArea.value = myTextArea.value.replace(/&\*/, '&');
  return true;
};

And of course, this does not replace a good server side validation

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜