Search code examples
javascriptasp.netrestrictckeditor.net

How to restrict user from deleting words with special characters from textbox


I am working in email CMS using ckeditor.net. At runtime user can change the body of email, I want to restrict user deleting all special words starting with @@ .

Here is example-

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

I don't want user to delete "@@comments" word and all "@@" characters in other email templates . Can you give any code in JavaScript?

At run time I replace "@@" words with some paragraph.


Solution

  • I haven't tested this code (just free-formed it into this response), but here's what I'd do.

    On the keydown method of the text input, you need to 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;
    }
    

    References

    Detect Backspace

    Get Caret Position

    Cancel the keydown event