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

Gar*_*ley 5 laravel laravel-4

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

Gar*_*ley 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;
});
Run Code Online (Sandbox Code Playgroud)

上面的代码定义了一个名为的验证规则not_contains- 它$words在fields字段中查找每个单词的存在,如果找到则返回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);
}
Run Code Online (Sandbox Code Playgroud)