Home / Admin / WPForms Custom Real-time Keyword Blocklist
Duplicate Snippet

Embed Snippet on Your Site

WPForms Custom Real-time Keyword Blocklist

This code snippet will add a custom validation rule to block specific keywords in real-time mirroring the behavior of Input Masks.

<10
Code Preview
php
<?php
/**
 * WPForms Custom Real-time Keyword Blocklist
 *
 * @link https://wpforms.com/developers/add-a-real-time-keyword-blocklist-to-a-single-line-text-field/
 */
function wpf_dev_realtime_keyword_blocker() {
    ?>
    <script type="text/javascript">
    jQuery(function($){
        // ------------------------------------------------------------
        // CONFIGURATION
        // ------------------------------------------------------------
        var targetFormID  = 100;  // Replace with your Form ID
        var targetFieldID = 1;    // Replace with your Field ID
        var blockedWords  = ['badword', 'spam', 'unwanted']; // List of keywords to block
        var customError   = 'This content contains restricted keywords.';
        // ------------------------------------------------------------
        // Only proceed if jQuery Validate is loaded
        if ( typeof $.fn.validate === 'undefined' ) {
            return;
        }
        // 1. Create the Custom Validation Method
        // This extends the validator used in wpforms.js
        $.validator.addMethod("restrictedKeywords", function(value, element) {
            // If field is empty/optional, pass validation (let 'required' rule handle empty)
            if ( this.optional(element) ) {
                return true;
            }
            var isClean = true;
            var lowerValue = value.toLowerCase();
            // Check the input against the blocked words list
            $.each(blockedWords, function(index, word) {
                if ( lowerValue.indexOf(word.toLowerCase()) !== -1 ) {
                    isClean = false;
                    return false; // Break the loop if a keyword is found
                }
            });
            return isClean;
        }, customError);
        // 2. Apply the Rule to the specific field
        // Construct the specific ID based on WPForms markup standards
        var fieldInput = $('#wpforms-' + targetFormID + '-field_' + targetFieldID);
        if ( fieldInput.length > 0 ) {
            fieldInput.rules('add', {
                restrictedKeywords: true,
                // You can override the message here dynamically if needed
                messages: {
                    restrictedKeywords: customError
                }
            });
        }
    });
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_realtime_keyword_blocker', 30 );

Comments

Add a Comment