I would like to prevent the user from pasting non allowed markup in a contenteditable
div.
I would like to restrict paste to bold, italic, strike, underline and links.
What is the best way (I'm using jQuery
) ?
This is not a duplicate of JQuery Text Editor Paste Without Formatting. I don't want to paste without formatting. I want to select / restrict to some markups.
I already read the following questions, none provides a clear answer:
Here Mudassar Ahmed Khan has explained with an example, how to disable or prevent CUT, COPY and PASTE operations in TextBox or TextArea using JavaScript. Cut, Copy and Paste operations in TextBox or TextArea can be performed using CTRL button or on Mouse Right Click.
Apply the onmousedown and onselectstart Events to the <body> or <div> tags to prevent text selection and copy/cut on your website. It override the default behavior of the browsers.
Cut, Copy and Paste operations in TextBox or TextArea can be performed using CTRL button or on Mouse Right Click. This article will illustrate how to disable Cut, Copy and Paste operations using both CTRL button and Mouse Right Click using JavaScript. Disable (Prevent) Cut, Copy and Paste using JavaScript.
If you need to disable text selection for the whole page, apply the user-select to the <body> element. Apply the onmousedown and onselectstart Events to the <body> or <div> tags to prevent text selection and copy/cut on your website. It override the default behavior of the browsers.
Restrict pasted content by listening to the editable element's paste
event. Inside this event, you can filter the data the user is attempting to paste by using a regular expression.
const el = document.querySelector('p');
el.addEventListener('paste', (e) => {
// Get user's pasted data
let data = e.clipboardData.getData('text/html') ||
e.clipboardData.getData('text/plain');
// Filter out everything except simple text and allowable HTML elements
let regex = /<(?!(\/\s*)?(a|b|i|em|s|strong|u)[>,\s])([^>])*>/g;
data = data.replace(regex, '');
// Insert the filtered content
document.execCommand('insertHTML', false, data);
// Prevent the standard paste behavior
e.preventDefault();
});
<p contenteditable>Try pasting content into this paragraph. The pasted content can include a <b>BOLD</b>, <i>ITALIC</i>, <s>STRIKE</s>, or <u>UNDERLINE</u>. It can also include a <a href='#'>LINK</a>.</p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With