1

In Gravity Forms I'd like to include a small keyword checker that is checking the user's message for "spammy" words and stops sending the entry to the admin. For this a hidden field changes it's value. I have this code included in my functions.php so far

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;
}

/*
* Our bad words validation function
*/


add_action('gform_pre_submission_1', 'keywords_check'); 

function keywords_check($validation_result){
$form = $validation_result["form"];


$stop_words = array(
    'outsource', 
    'Madam', // this covers all variations of 'Sir/Madam' 'Sir /Madam' 'Sir/ Madam' 'Sir / Madam' etc
    'SEO',
    'long term relationship',
);

$stop_id = array();

foreach($_POST as $id => $post)
{
    if(strpos_arr($post, $stop_words))
    {
        /*
         * We have a match so store the post ID so we can count it
         */ 
         $stop_id[] = $id;
    }
}

if(sizeof($stop_id) > 0)
{
    $validation_result['is_valid'] = false;


    $_POST['input_55'] = "No";

}

}

There seems to be a problem with the part in the very beginning of this code, especially with

foreach($needle as $what) {
    if(($pos = stripos($haystack, $what))!==false) return $pos;
}

After sending the form I get the following warning

Warning: stripos() expects parameter 1 to be string, array given on line 109

I have several php noob trial and error hours behind me before asking this question. Can anyone help me out with this?

0

I have a plugin that will also handle this via the default WordPress comment blacklist functionality: https://gravitywiz.com/documentation/gravity-forms-comment-blacklist/

0

The problem is in function strpos_arr. If your bad word is in $pos = 0 than the output will always be false. Replace the line:

if(($pos = stripos($haystack, $what))!==false) return $pos;

with:

if(($pos = stripos($haystack, $what))!==false) return true;

Your keywords_check function can be much simplified by using it as Gravity Forms field validation filter:

function keywords_check( $result, $value, $form, $field ) {
    $stop_words = array(
        'outsource', 
        'Madam', // this covers all variations of 'Sir/Madam' 'Sir /Madam' 'Sir/ Madam' 'Sir / Madam' etc
        'SEO',
        'long term relationship',
    );

    if ( strpos_arr( $value, $stop_words ) ) {
        $result['is_valid'] = false;
        $result['message'] = 'Illegal words entered';
    }
    return $result;
}
add_filter( 'gform_field_validation_2_4', 'keywords_check', 10, 4 );

Notice two numbers in 'hook' name in this example. 2 - form id, 4 - field id. Adjust those numbers to match your form.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.