Laravel Custom Validation Rules should be lowercase? - laravel

I have model, and it has several field names, and 'lastName' is among them.
In my FormRequest file, I have rules and messages for this field:
$rules = ['lastName.*' => 'lastName_fail: index'];
$messages = ['lastName.*lastName_fail' => This lastName has different value in DB!'];
When I am submitting a form, filling the 'lastName' field with intentionally 'wrong' value, it doesn't pass validation, and returns error message:
validation.last_name_fail
(which is not what's in $messages).
But when I change $rules and $messages to:
$rules = ['lastName.*' => 'lastname_fail: index'];
$messages = ['lastName.*lastname_fail' => This lastName has different value in DB!'];
(so the actual "rule" is now lowercase "lastname_fail"), it outputs what i want:
This lastName has different value in DB!
from this I may conclude that Laravel's validation rule name may be
only lowercase.
Is it declared anywhere in documentation?
If so, maybe it helps someone.

It is not mentioned in the documentation. However, there is a naming pattern for both validation rule method name and rule name.
Rule Method Name:
It must have validate prefix and the rest of it must be in Camel Case.
Rule Name:
It will be in lowercase without the validate prefix and each word will be separated by an underscore.
So if you want to add alpha_dash_spaces validation rule then the corresponding method will be named validateAlphaDashSpaces().

Simply parse $request[data] before Validator
use Illuminate\Support\Str;
$request['name_it'] = Str::lower($request['name_it']);
$request['name_en'] = Str::lower($request['name_en']);
$validator = Validator::make($request->all(), [
'name_it' => ['required', 'string', 'max:255', 'unique:categories'],
'name_en' => ['required', 'string', 'max:255', 'unique:categories'],
]);
if ($validator->fails()) {
return redirect()
->back()->withErrors($validator)
->withInput();
}

Related

Laravel validate rule

I have two datepicker input fields: from and to. To ensure that field value to is greater than field value from, I use the after validation rule. Everything is fine up until I leave the from input value null. Because I am applying the validation rule using the input value from.
How can I combine the required and after validation rules without running into this problem?
$from = $request->input('from');
$from = Carbon::createFromFormat('Y-m-d\TH:i', $from)->format('Y-m-d H:i A');
$attributes= request()->validate([
'from' => 'required|date',
'to'=> 'nullable|date|after:'.$from,
]);
Data missing error while from input value is empty.
The laravel validation rule allows you to compare a field against another field. So you can simply add: after:from
See the documentation here.
$attributes = request()->validate([
'from' => 'required|date',
'to'=> 'nullable|date|after:from',
]);

How to validate several rules with 'required_if' on Laravel 5.5?

I am trying to validate the 'uuid' field so that it is mandatory if the 'typeUUID' field is marked 'type1'.
$validator = Validator::make($request->all(), [
'uuid' => 'required_if:typeUUID,==,type1|alpha_dash|size:36',
]);
If I select the value 'type1' it indicates that the field is mandatory, and when I set another value that is not mandatory, it validates' alpha_dash 'and' size: 36 and does not accept the field since it is sent empty.
What is the right way?
I know I could do it with a condition by checking the type at the beginning and then applying one or more rules. But I would like to know the correct way to do it.
I found the solution, is to add the rule 'nullable' after the rule 'required_if'.
$validator = Validator::make($request->all(), [
'uuid' => 'required_if:typeUUID,==,type1|nullable|alpha_dash|size:36',
]);

Seeding validation array

I am creating a lot of questions via a seeder. The format I am doing is this
DB::table('questions')->insert([
'name' => 'questionOne',
'rule' => 'nullable|max:50|regex:/(?=.)^\£?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/'
]);
Whereby I provide a field name and a validation rule. I was noticing that when applying the above rule, the validation would fail, stating
preg_match(): No ending delimiter '/' found
I done some research and found out that
When using the regex pattern, it may be necessary to specify rules in
an array instead of using pipe delimiters, especially if the regular
expression contains a pipe character.
As recommended, I changed my seeder to this
DB::table('questions')->insert([
'name' => 'questionOne',
'rule' => ['nullable|max:50|regex:/(?=.)^\£?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/']
]);
However, when I try to seed with the above, I get an Array to String conversion error. The way I am applying the validation is like so
$rules = [];
$questions = Question::all();
foreach ($questions as $question) {
if (!empty($question->rule)) {
$rules["questions.{$question->id}"] = $question->rule;
}
}
$this->validate($request, $rules);
Is there any way I can get the above regex to work? One point to note is that only a few questions have this regex, if that matters?
Thanks
When using the regex pattern, it may be necessary to specify rules in an array instead of using pipe delimiters, especially if the regular expression contains a pipe character.
This is referring to the $rules variable passed into $this->validate; your regex pattern contains a pipe character | which interferes with Laravel's ability to split up the rule string into an array internally.
Storing the rules in string format with pipe separators also makes it difficult for you to split them into an array upon retrieval from the DB. I'd recommend storing them as a similarly delineated structure like JSON, which would make your seeder:
DB::table('questions')->insert([
'name' => 'questionOne',
'rule' => json_encode([
'nullable',
'max:50',
'regex:/(?=.)^\£?(([1-9][0-9]{0,2}(,[0-9]{3})*)|[0-9]+)?(\.[0-9]{1,2})?$/'
])
]);
and validation:
$rules = [];
$questions = Question::all();
foreach ($questions as $question) {
if (!empty($question->rule)) {
$rules["questions.{$question->id}"] = json_decode($question->rule, true);
}
}
$this->validate($request, $rules);
You would also want to change the rule column type to JSON in your questions table migration.
To further simplify the code, you could make use of Laravel's attribute casting feature which claims to handle the json_encode/json_decode for you:
protected $casts = [
'rule' => 'array',
];

How to allow empty value for Laravel numeric validation

How to set not require numeric validation for Laravel5.2? I just used this Code but when i don't send value or select box haven't selected item I have error the val field most be numeric... I need if request hasn't bed input leave bed alone. leave bed validate ...
$this->validate($request, [
'provinces_id' => 'required|numeric',
'type' => 'required',
'bed' => 'numeric',
]);
If I understood you correctly, you're looking for sometimes rule:
'bed' => 'sometimes|numeric',
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
In Laravel 6 or 5.8, you should use nullable. But sometimes keyword doesn't work on that versions.
Use sometimes instead of required in validation rules. It checks if only there is a value. Otherwise it treats parameter as optional.
You may need nullable – sometimes and
present didn't work for me when combined with integer|min:0 on a standard text input type - the integer error was always triggered.
A Note on Optional Fields
By default, Laravel includes the TrimStrings and ConvertEmptyStringsToNull middleware in your application's global middleware stack. These middleware are listed in the stack by the App\Http\Kernel class. Because of this, you will often need to mark your "optional" request fields as nullable if you do not want the validator to consider null values as invalid.
Tested with Laravel 6.0-dev
Full list of available rules
In laravel 5.5 or versions after it, we begin to use nullable instead of sometimes.
according to laravel documentation 8 you must to set nullable rule
for example:
$validated = $request->validate([
'firstName' => ['required','max:255'],
'lastName' => ['required','max:255'],
'branches' => ['required'],
'services' => ['required' , 'json'],
'contract' => ['required' , 'max:255'],
'FixSalary' => ['nullable','numeric' , 'max:90000000'],
'Percent' => ['nullable','numeric' , 'max:100'],
]);
in your case :
$this->validate($request, [
'provinces_id' => 'required|numeric',
'type' => 'required',
'bed' => 'nullable|numeric',
]);

Laravel 5 validation rules

previously I have used validation within a Request class e.g.
public function rules()
{
return [
'userName' => 'required', 'min:3',
'userEmail' => 'required|email',
'departmentId' => 'required',
'slug' => 'required',
];
}
But I now have another form but I can't see any options within the documentation that might help me.
Basically, lets say I have a form with the same fields as the validation above. The only time validation should fail is if ALL fields contain absolutely no data. So if I put something like "hi" within the slug input and submit, it should pass the validation.
Would something like this be possible?
Thanks
You can probably use the required_without_all validation rule.
http://laravel.com/docs/5.1/validation#rule-required-without-all
The field under validation must be present only when all of the other
specified fields are not present.
It would give you something like
public function rules()
{
return [
'userName' => 'required_without_all:userEmal,departmentId,slug','min:3',
'userEmail' => 'required_without_all:userName,departmentId,slug|email'
...
];
}
But it's not very handy if you have a lot of fields.
If you have to deal with many fields, creating a custom validator might be a better solution.
http://laravel.com/docs/5.1/validation#custom-validation-rules

Resources