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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With