如何验证输入不包含特定单词?

问题描述 投票:4回答:2

在我的注册表单中,我有一个昵称字段,用户可以在其中输入文本以在我的网站上标识自己。在过去,一些用户输入了昵称,其他人可能会觉得这些昵称令人反感。 Laravel为表单提供验证功能,但是如何确保表单字段不包含用户可能会觉得冒犯的字词?

laravel laravel-4
2个回答
11
投票

虽然Laravel包含了广泛的验证规则,但检查给定列表中是否存在单词不是其中之一:

http://laravel.com/docs/validation#available-validation-rules

但是,Laravel还允许我们创建自己的自定义验证规则:

http://laravel.com/docs/validation#custom-validation-rules

我们可以使用Validator::extend()创建验证规则:

Validator::extend('not_contains', function($attribute, $value, $parameters)
{
    // Banned words
    $words = array('a***', 'f***', 's***');
    foreach ($words as $word)
    {
        if (stripos($value, $word) !== false) return false;
    }
    return true;
});

上面的代码定义了一个名为not_contains的验证规则 - 它在字段值中查找$words中每个单词的存在,如果找到则返回false。否则返回true表示验证已通过。

然后我们可以正常使用我们的规则:

$rules = array(
    'nickname' => 'required|not_contains',
);

$messages = array(
    'not_contains' => 'The :attribute must not contain banned words',
);

$validator = Validator::make(Input::all(), $rules, $messages);

if ($validator->fails())
{
    return Redirect::to('register')->withErrors($validator);
}

0
投票

在Laravel 5.7和可能的早期版本中,您可以使用内置的not_regex规则来检查一些字符串。例如,在使用validate方法的控制器中。验证需要狗名称的表单输入。 :

...
public function update(Request $request) {
  $custom_validation_messages = [
    'not_regex' => "C'mon! Be original. Give your dog a more interesting name!"
  ];
  $this->validate($request, [
    'pet_name' => [ 'not_regex:/^(fido|max|bingo)$/i' ],
  ], $custom_validation_messages);

  ...
}

在这种情况下,如果提交的'pet_name'值为:

  • 信任
  • FIDO
  • MAX
  • MAX
  • 答对了
  • 答对了
  • 等等

然后验证将失败。

对于这个的逆,即你只想要Fido,Max或Bingo,那么你可以像这样使用regex规则:

[ 'regex:/^(fido|max|bingo)$/i' ]

Laravel Validation (not regex)

© www.soinside.com 2019 - 2024. All rights reserved.