How can I validate input does not contain specific words? - laravel

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);
}

In Laravel 5.7 and possibly earlier versions, you could use the built in not_regex rule to check for some strings. Like this for example, within a controller using the validate method. Validate form input that expects a name for a dog. :
...
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);
...
}
In this case if the submitted 'pet_name' value is:
fido
FIDO
MaX
MAx
BinGO
bingo
etc.
Then validation will fail.
For the inverse of this, i.e. you only want Fido, Max or Bingo then you could use the regex rule like so:
[ 'regex:/^(fido|max|bingo)$/i' ]
See Laravel Validation (not regex).

Related

Use `trans_choice()` in request validation messages with validation rule parameter

I need a request validation rule to return a custom message upon failure, and since the field being validating is an array with a min:x rule i'd like to have a custom message for both singular and plural variations.
I'm just wondering how to pass to the trans_choice() function the :min parameter from the validation rule:
Translation file:
'array' => [
'field' => [
'min' => 'You need to select at least one item.|you need to select at least :min items',
],
],
Request message() method:
public function messages() {
'my.array.field.min' => trans_choice('translations::array.field.min', ???),
}
It seems like there's nothing built into Laravel to use trans_choice whenever you can pluralise a translation string.
A way you could solve that is by temporarily (or permanently, whatever fits your use-case) changing the replacer for the min rule to something like this:
Validator::replacer('min', function ($message, $attribute, $rule, $parameters, $validator) {
$minValue = $parameters[0];
$message = Str::contains($message, '|')
? trans_choice($message, $minValue)
: $message;
return str_replace(':min', $minValue, $message);
});
Or by extending the Validator factory to work in your favour, but since that requires you to change many of it's methods I don't really recommend that.

Laravel email validation issue

Default Laravel Validation class allows strange emails. Here is the Validation rules that I defined:
return Validation::make($data, [
'email' => 'required|string|email|max:100|unique:customers,email'
]);
When I tried to use some strange email like:
aaaa?#%&'#şğüçi̇ö.com it passes the validation. However the non latin characters on the email is converted before DB insert. So the email address on the database doesn't match with the original one.
In order to prevent this I want to disallow the usage of non-latin characters after the # symbol. I tried the custom rule which is:
public function passes($attribute, $value)
{
return filter_var($value, FILTER_VALIDATE_EMAIL)
&& preg_match('/#.+\./', $value);
}
but it is not working. It would be good to get some help on this.
Edit 1
Thanks for your responses! But apparently the reason that the custom validator not taking action is that Laravel sanitizes all input data before any manipulation. That's why after it converts the non-latin characters, preg_replace() returns 1 all the time since there is no non-latin characters on the input. First of all I need to find a solution to this and prevent Laravel to sanitize the input.
From your question I understand you already created a custom Validation Rule and use it like
...
'email' => [
'required',
'string',
...
new ValidateLatinEmail()
]
As you can see here, your RegEx is the problem with that validation
This one should work:
public function passes($attribute, $value)
{
return filter_var($value, FILTER_VALIDATE_EMAIL)
&& preg_match('/#[\x00-\x7F]*\./', $value);
}

Laravel custom validation: only validate input if input given

So I followed this tutorial to learn how to upload images with Laravel using Vue: Image upload and validation using Laravel and VueJs
Everything works fine, but I want to make the image upload optional. Now the custom validation fails for the AppServiceProvider. if it does not have any input then i get this error
trying to access an attribute inside an array that does not exist. Undefined offset: 1
I could avoid the error by asking
if (request('image'))
In the controller and applying the validation for the other fields only if no image is given. However, this gets incredibly messy.
So I am looking for a way to get the custom validation rule working if there is no input. Or is that the wrong way?
Here is the custom validation rule:
public function boot()
{
Validator::extend('image64', function ($attribute, $value, $parameters, $validator) {
$type = explode('/', explode(':', substr($value, 0, strpos($value, ';')))[1])[1];
if (in_array($type, $parameters)) {
return true;
}
return false;
});
Validator::replacer('image64', function($message, $attribute, $rule, $parameters) {
return str_replace(':values',join(",",$parameters),$message);
});
}
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule to your rule list:
$v = Validator::make($data, [
'email' => 'sometimes|required|email',
]);
In the example above, the email field will only be validated if it is present in the $data array.
Reference: Conditionally Adding Rules
Laravel provides a validation called 'nullable' in case other validation rules should not be run if the given value is null: A Note On Optional Fields

Laravel Validation sometimes rules for date validation

I currently have a validation rule which looks like this:
public function rules()
{
return [
'startDate' => 'required|sometimes|before_or_equal:endDate',
'endDate' => 'sometimes|required|after_or_equal:startDate',
];
}
The sometimes option works as I understand it on the basis that if the field is present, run the validation rule. However, if the end date is not sent or is null, my before or equal rule kicks in and fails. In some instances within my application, end date will be null. Is there a way to 'cancel' the startDate validation rule in this instance or would I need to create a custom validator for this purpose?
something like before_or_equal_when_present ?
You can use IFs to add and manipulate rules in the rules function. You can access the inputs there referring to $this as the request itself:
public function rules()
{
$rules = [
'startDate' => 'required|sometimes|before_or_equal:endDate',
'endDate' => 'sometimes|required|after_or_equal:startDate',
];
if( $this->input('endDate') > 0)
$rules['endDate'] = "rule". $rules['endDate']
return $rules;
}
This is just a mockup just to let you know that you can manipulate and have access to the fields passed.

Yii2 compare email without case sensitive

I use the simple compare validation rule offered by Yii2 like this:
[confirm_email', 'compare', 'compareAttribute'=>'email', 'message'=>"Emails don't match"],
The problem is that this rule compares two emails 100% including Case Sensitive which means email#test.com and email#Test.com will generate validation error.
Is there a way to remove this Case Sensitive comparison from this rule?
strcasecmp does not handle multibyte characters, read this
suggestion is to use strtolower()
you might also be interested in yii's input filter, to transform input to lowercase, like this:
[
// both email fields tolower
[['email', 'confirm_email'], 'filter', 'filter' => 'strtolower'],
// normalize "phone" input
['phone', 'filter', 'filter' => function ($value) {
// normalize phone input here
return $value;
}], ]
You can create custom validation if you want.
public function rules()
{
return [
// an inline validator defined as the model method validateEmail()
['email', 'validateEmail'],
];
}
public function validateEmail($attribute, $params)
{
if (strcasecmp($this->attribute, $this->confirm_email) == 0) {
$this->addError($attribute, 'Username should only contain alphabets');
}
}
It will compare emails with binary safe case-insensitive.

Resources