Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I validate input does not contain specific words?

In my signup form I have a nickname field that users can enter text in to identify themselves on my site. In the past some users have entered nicknames which others might find offensive. Laravel provides validation functionality for forms, but how can I ensure that a form field doesn't contain words users might find offensive?

like image 796
Gareth Oakley Avatar asked Aug 06 '13 12:08

Gareth Oakley


1 Answers

Whilst Laravel has a wide range of validations rules included, checking for the presence of a word from a given list isn't one of them:

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

However, Laravel also allows us to create our own custom validation rules:

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

We can create validation rules using 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;
});

The code above defines a validation rule called not_contains - it looks for presence of each word in $words in the fields value and returns false if any are found. Otherwise it returns true to indicate the validation passed.

We can then use our rule as normal:

$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);
}
like image 62
Gareth Oakley Avatar answered Sep 20 '22 22:09

Gareth Oakley