如何只允许包含某些单词的表单提交

问题描述 投票:0回答:1

我对表单使用 Joomla 扩展(转换表单),并且希望仅允许用户在将给定列表中的某个关键字键入给定文本字段(某种代码)时提交该表单。扩展本身允许一些 php 代码。

我发现下面的 PHP 代码,当用户从“不允许的单词”列表中输入单词时,它将阻止用户提交。

任何人都可以帮忙将其更改为“允许的单词”列表吗?

    $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);
      }
    }
validation joomla form-submit
1个回答
0
投票

一种方法可以从字符串中删除白名单单词,最后检查最终字符串是否为空:

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

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

if (trim(str_replace($allowed_words, '', $input)) !== '') {
    throw new Exception($error_message);
}
© www.soinside.com 2019 - 2024. All rights reserved.