How to Block Form Submissions Containing Profanity

Overview

Would you like to block your forms from sending if they contain profanity? You can easily set up a list of profanity words that will halt any form submission if they are found inside your Paragraph Text or in a Single Line Text field using a small code snippet. In this tutorial we’ll walk you through the steps on how achieve this with PHP.

Setup

First, come up with a list of words you want to add to your profanity filter. Once you have that list, you can add one or both of the code snippets below to your site.

You will just add each words to your $blocked_words separated by a comma.

Adding the Paragraph Text Code Snippet

/**
 * Prevent profanity words from Paragraph Text form fields.
 *
 * @link https://wpforms.com/developers/how-to-block-form-submissions-containing-profanity/
 *
 */

function wpf_dev_profanity_filter_paragraph( $field_id, $field_submit, $form_data ) {
    //Create your list of profanity words separated by commas
	$blocked_words = array( 
		'badword1', 
		'badword2'
	);

	foreach( $blocked_words as $word ) {
		if(strpos($field_submit, $word) !== FALSE ) {
			wpforms()->process->errors[ $form_data['id'] ][ $field_id ] = esc_html__( 'No profanity allowed.', 'wpforms' );
			return;
		}
	}

}

add_action( 'wpforms_process_validate_textarea', 'wpf_dev_profanity_filter_paragraph', 10, 3 );

There will be a message under the Paragraph Text form field stating the form can't be submitted with profanity.

Adding the Single Line Text Code Snippet

/**
 * Prevent profanity words from Single Line Text form fields.
 *
 * @link https://wpforms.com/developers/how-to-block-form-submissions-containing-profanity/
 *
 */

function wpf_dev_profanity_filter_single_text( $field_id, $field_submit, $form_data ) {
    //Create your list of profanity words separated by commas
	$blocked_words = array( 
		'badword1', 
		'badword2'
	);

	foreach( $blocked_words as $word ) {
		if(strpos($field_submit, $word) !== FALSE ) {
			wpforms()->process->errors[ $form_data['id'] ][ $field_id ] = esc_html__( 'No profanity allowed.', 'wpforms' );
			return;
		}
	}

}

add_action( 'wpforms_process_validate_text', 'wpf_dev_profanity_filter_single_text', 10, 3 );

There will be a message under the Single Line Text form field stating the form can't be submitted with profanity.

And that’s it! You’ve now created and implemented a profanity filter for your Single Line and Paragraph Text form fields. Would you like to block certain email domains from submitting forms on your site as well? Take a look at the snippet on How to Restrict Email Domains.

Action references: