How To Block Pasting To Stop Contact Form Spam

RMAG news

There are two ways a spammer can paste something into a field, the keyboard and the context menu. The keyboard paste is most often accomplished using the well known ctrl-v command and the context menu paste is accomplished by pressing right click on the mouse within the field and then selecting paste from the context menu. We need to prevent both if we want to stop spammers from blowing up our inbound forms.

To specifically target textarea fields that have the class wpcf7-textarea (which is commonly used by Contact Form 7), you can adjust the JavaScript snippet to apply only to these textarea elements. Here is the updated JavaScript that includes preventing copy, paste, cut, and disabling the context menu (right-click) actions specifically on textarea fields with the wpcf7-textarea class:

<script type=”text/javascript”>
document.addEventListener(‘DOMContentLoaded’, function() {
var textareas = document.querySelectorAll(‘.wpcf7-textarea’); // Target only elements with the ‘wpcf7-textarea’ class

textareas.forEach(function(textarea) {
// Disable paste into textarea
textarea.addEventListener(‘paste’, function(event) {
event.preventDefault();
alert(‘Pasting text is not allowed in this field.’);
});

// Disable cut from textarea
textarea.addEventListener(‘cut’, function(event) {
event.preventDefault();
alert(‘Cutting text is not allowed in this field.’);
});

// Disable right-click on textarea
textarea.addEventListener(‘contextmenu’, function(event) {
event.preventDefault();
alert(‘Right-click is disabled on this field.’);
});
});
});
</script>

How to Add This Script to Your WordPress Site

You can add this JavaScript to your WordPress site in a few different ways:

Via the Theme’s Footer or Header:

Go to Appearance > Theme Editor in your WordPress dashboard.
Locate and open the footer.php file (or header.php as preferred).
Paste the script above just before the closing

Leave a Reply

Your email address will not be published. Required fields are marked *