1. Home
  2. /
  3. Web Design & Development
  4. /
  5. WordPress
  6. /
  7. Gravity Forms – Prevent Spam form submissions using Stop Words or disallowed keywords

Gravity Forms – Prevent Spam form submissions using Stop Words or disallowed keywords

Gravity Forms Prevent Spam form submissions using Stop Words or disallowed keywords

Sometimes even after using Google ReCaptcha and other spam protections on the website forms, we tend to receive submissions related to promotional or marketing events (cold campaign), spam submissions containing obscene, vulgar, or otherwise offensive content. In such cases, if you are using the Gravity Forms on your website.. you can use the following approach to block all such form submissions.

To stop form submissions with Profanity (Bad Words), you need to add all the possible stop words in the WP backend – disallowed comment keywords.

Settings >> Discussion

Click on Disallowed Comments Keys and, add all such words which you don’t want in your form field submissions.

Gravity Forms - Prevent Spam form submissions

Once you’re done adding all the stop words.

Open your themes functions.php file and add the below script at the bottom of the script before closing of any PHP tag.


/* 
 * Search bad words in the entered string
 */
function strpos_arr($haystack, $needle) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $what) {
        if(($pos = stripos($haystack, $what))!==false) return $pos;
    }
    return false;
}
 
/*
 * Bad words validation function
 */
add_filter('gform_validation', 'smartland_spam_validation');
function smartland_spam_validation($validation_result){ 
    $form = $validation_result["form"];
 
	/* $stop_words = array(
		'outsource',
		'Sir/Madam',
		'Sir/ Madam',
		'Sir / Madam',
		'Sir /Madam',
		'long term relationship',
	); */
	
	
	$stop_words = get_option('disallowed_keys');
	$stop_words = explode("\n", $stop_words);
 
	$stop_id = array();
 
	foreach($_POST as $id => $post)
	{
		
		if(strpos_arr($post, $stop_words)!==false)
		{
			 $stop_id[] = $id;
		}
	}

	if(sizeof($stop_id) > 0)
	{
		$validation_result['is_valid'] = false;
 
		foreach($form['fields'] as &$field) 
		{
			foreach($stop_id as $id)
			{
				$the_id = (int) str_replace('input_', '', $id);
 
				if($field['id'] == $the_id)
				{
					$field['failed_validation'] = true;
					$field['validation_message'] = 'Please do not send us unsolicited messages';
				}
			}
		}
	}
 
    //assign modified $form object back to the validation result
    $validation_result["form"] = $form;
    return $validation_result;
 
}

After you’re done adding the above piece of code in your functions.php. You can now test the forms on the website which are built using gravity forms.

Conclusion:

The outcome of this script will prevent users to pass the form validations and submit the form.

Leave a Reply

Reviews & Ratings Get your stoe online with Shopify in 60 minutes Shop Now