How to only allow form submission containing certain words

25 Views Asked by At

I use a Joomla Extension for a form (Convert Forms), and want to allow only users to submit that form when typeíng a certain keyword out of a given list into a given text field (kind of a code). The extension itself allows some php code.

I found the below PHP code, that will block users from submitting, when they type a word from a list of "not allowed words".

Can anyone help to change this into a list of "allowed words"?

    $not_allowed_words = [
      'dog',
      'cat',
      'elephant'
    ];

    $field_name = 'text';

    $error_message = 'Your text contains words that are not allowed.';

    foreach($not_allowed_words as $word)
    {
      if (stripos($post[$field_name], $word) !== false)
      {
        throw new Exception($error_message);
      }
    }
1

There are 1 best solutions below

1
Justinas On

One approach can be deleting whitelist words from string and finally checking if final string is empty:

$allowed_words = [
    'dog',
    'cat',
    'elephant'
];

$input = strtolower($post[$field_name]);

if (trim(str_replace($allowed_words, '', $input)) !== '') {
    throw new Exception($error_message);
}