javascripthtmlcss

Prevent users from pasting images into contenteditable-div


I have a div, which is defined like this: <div contenteditable="true" id="call-text-form-textarea"></div> But I want to prevent the user, pasting images into it.

Is there a option, to prevent it with html? Or maybe I cloud JavaScript for this?


Solution

  • I found an answer to my question based on Karishma Shukla's answer and the following link: JavaScript get clipboard plain text...

    $("#call-text-form-textarea").bind("paste", function(e){
        var pastedData = e.originalEvent.clipboardData.getData('text');
        var regex = /^[a-zA-Z0-9@  `!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?~]+$/;
        
        if (regex.test(pastedData) !== true) {
                e.preventDefault();
                setTimeout(function(){
                    $("#inputText").html('');
                },100)
        }
    });