如何限制用户从文本框中删除带有特殊字符的单词

时间:2012-07-13 10:42:56

标签: javascript asp.net restrict ckeditor.net

我正在使用ckeditor.net在电子邮件CMS中工作。 在运行时,用户可以更改电子邮件正文,我想限制用户删除所有以@@。

开头的特殊单词

以下是示例 -

Email Alert! :<br />
<br />
**@@Comments**<br />
<br />
Please do not reply to this email.

我不希望用户删除其他电子邮件模板中的“@@ comments”字样和所有“@@”字符。 你能用JavaScript代码吗?

在运行时我将“@@”字替换为某段。

1 个答案:

答案 0 :(得分:2)

我没有测试过这段代码(只是自由形成了这个代码),但这就是我要做的。

在文本输入的keydown方法中,您需要listen for the backspace key

var input = document.getElementById('myInput');

input.onkeydown = function() {
    var key = event.keyCode || event.charCode;

    // Detect Backspace (8) & Delete (46) keys
    if( key == 8 || key == 46 ){

       var caretPos = getCaretPos(input);

       // Read backward from the caret position
       // until you hit a space or index 0:
       while ( (input.value[caretPos] != " ") && (caretPos > 0)  ){
          caretPos--;
       }

       // Once you hit the space or index 0, read forward two characters 
       // to see if it === "@@".  If both chars are "@", cancel 
       // the keydown event.  You should probably do some bounds checking
       // here.  Could also be done with String.subtring
       if ( input.value[(caretPos + 1)] == "@" && 
            input.value[(caretPos + 2)] == "@" )
       {
          return false;
       }
    }

};


function getCaretPos(input) {
    // Internet Explorer Caret Position (TextArea)
    if (document.selection && document.selection.createRange) {
        var range = document.selection.createRange();
        var bookmark = range.getBookmark();
        var caret_pos = bookmark.charCodeAt(2) - 2;
    } else {
        // Firefox Caret Position (TextArea)
        if (input.setSelectionRange)
            var caret_pos = input.selectionStart;
    }

    return caret_pos;
}

参考

Detect Backspace

Get Caret Position

Cancel the keydown event