I have inputs, some of them are array inputs (e.g. <input name="test[]">) and some are normal ones.
Fields have some specific rules, but all of them share 2 rules together.
I want that same validation rule to be applied to all fields instead of copying the same thing again and again for like 10+ fields.
I tried:
$rules = [
'*.*' => ['max:100', new CustomRule], // Apply to all
'name1' => ['array'],
'name1.*' => ['specific_rule'],
]
but it didn't work, then I moved that *.* to bottom like this:
$rules = [
'name1' => ['array'],
'name1.*' => ['specific_rule'],
'*.*' => ['max:100', new CustomRule], // Apply to all
]
and then suddenly it works!
A little confused about why it doesn't work on top, and I'm not sure if this is the right way to do this.
Please advise.
Edit:
The whole thing (removed some of the rules to simplify):
$data = json_decode($request->getContent(), true);
$rules = [
'contact' => ['required', 'array'],
'contact.name' => ['required', 'string', 'max:255'],
'contact.email' => ['required', 'email', 'unique:users,email', 'max:255'],
'subscription' => ['required', 'array'],
'subscription.type' => ['nullable', 'integer'],
'*.*' => [new CustomRule], // Works when it's here, doesn't work on top, this is a Regex rule, looking for some invalid characters in all inputs.
];
$validator = Validator::make($data, $rules);
if($validator->fails())
{
return response()->json($validator->messages(), 400);
}
Related
I tried insert ads using validation system but its give me error:
Argument 1 passed to Illuminate\Validation\Factory::make() must be of the type array, object given, called in D:\wamp\www\pagination\vendor\laravel\framework\src\Illuminate\Support\Facades\Facade.php on line 261
AdsController.php
public function store(Request $request)
{
$file = new File($request->all());
$file->user_id = Auth::user()->id;
$validator = Validator::make($file->all(), [
'category_id'=>['bail','required'],
'titre' => ['bail', 'exclude_unless:category_id,1', 'required', 'string', 'min:3', 'max:255'],
'name' => ['bail', 'exclude_unless:category_id,2', 'required', 'string', 'min:3', 'max:255'],
'last' => ['bail', 'exclude_unless:category_id,1', 'required', 'string', 'min:3', 'max:255'],
]);
File::create($validator->validated());
return Redirect::to("/")
->withSuccess('Great! file has been successfully uploaded.');
}
You just need to pass $request->all() as the first argument to Validator::make().
...
$validator = Validator::make($request->all(), [
/* validation rules */
];
...
And I think 'title' is misspelled in your validation rules (titre);
sometimes this errors comes when you use this:
'$validator = Validator::make($request->all, [
'file' => 'requeired|max:7000|mimes:xlsx,xls,csv'
]);' instead of this $validator = Validator::make($request->all(), [
'file' => 'requeired|max:7000|mimes:xlsx,xls,csv'
]);
I'm trying to apply these validation rules to my controller function, but any of the rules are not applying
Here is my code
if($request->hasFile('propic'))
{
$this->validate($request, [
'name' => 'required', 'alpha','min:2', 'max:255',
'last_name' => 'required', 'alpha','min:5', 'max:255',
'mobile' => 'required', 'string','min:10','max:14', 'regex:/\+(9[976]\d|8[987530]\d|6[987]\d|5[90]\d|42\d|3[875]\d|
2[98654321]\d|9[8543210]|8[6421]|6[6543210]|5[87654321]|
4[987654310]|3[9643210]|2[70]|7|1)\d{1,14}$/',
'email' => 'required', 'string', 'email', 'max:255', 'unique:users,email,'.$setting->id.'',
'propic' => 'required','image','mimes:jpeg,png,jpg,gif,svg','max:2048',
]);
$imageName = time().'.'.$request->propic->extension();
$request->propic->move(public_path('propics'), $imageName);
$setting->propic=$imageName;
$setting->name=$request->input('name');
$setting->last_name=$request->input('last_name');
$setting->mobile=$request->input('mobile');
$setting->email=$request->input('email');
$setting->update();
return Redirect::back()->with('success',__('sentence.User updated successfully'));
}
At time of writing, there's two accepted formats for passing in validation rules:
As an array of strings (note the square brackets, which is what you are missing currently):
$this->validate($request, [
'name' => ['required', 'alpha','min:2', 'max:255'],
...
]);
As a single pipe-delimited string:
$this->validate($request, [
'name' => 'required|alpha|min:2|max:255',
...
]);
I am using Laravel Auth to make authentication. I need to compare a field input (Phone Number) with a regex expression in validator method. How can I do this. Below is the method code I am using,
(Currently I am hard coding my number "0312 1234567" How can I use a regex expression here?)
public function validator(array $data)
{
if($data['emailOrNumber'] == "03121234567") {
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'emailOrNumber' => ['required', 'numeric','unique:usersNew,phone'],
'password' => ['required', 'string', 'min:8'],
'surname2' => ['required', 'string', 'max:255']
]);
}
}
If you want to check against a regex, you can use the Regex validation rule.
You could use
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'emailOrNumber' => ['required', 'numeric','unique:usersNew,phone', 'regex:/(\+[0-9]{2})?[0-9]{10,12}/g'],
'password' => ['required', 'string', 'min:8'],
'surname2' => ['required', 'string', 'max:255']
]);
Little hint, I wouldn't save the email or phone number in the same column in the database. These are two completely different things, so I would save them in differrent columns. You can always leave on of the two columns empty.
You can read more about this validation on https://laravel.com/docs/5.7/validation#rule-regex
I'm trying to validate an array within the update method which means I need to ignore the id's of the rows so that it doesn'r return the error:
contactName has already been taken
Here is my validation from my update method of my controller:
public function update($id, Request $request)
{
$brand = Brand::findOrFail($id);
$request->validate([
'name' => ['required', 'string', 'max:255', Rule::unique('brands')->ignore($id)],
'contactNames' => ['required', 'array'],
'contactNames.*' => ['required', 'max:255', 'string', 'distinct', Rule::unique('brand_managers', 'name')->ignore( //what goes here? )],
'emails' => ['required', 'array'],
'emails.*' => ['required', 'max:255', 'email', 'distinct', Rule::unique('brand_managers', 'email')->ignore( //what goes here? )],
'contactNumbers' => ['array'],
'contactNumbers.*' => ['numeric'],
'groupCheckbox' => ['required', 'min:1'],
]);
}
With the unique validation rule on 'name' I can ignore the id that is coming with the $id using route model binding, but with the contactNames and contactEmails this needs to check a table that has a manyToMany relationship -
how do I ignore the id's of the brand_manager rows for multiple validation checks?
I will try and edit my question for more clarity
Thanks!
You can easily create validation rules dynamically as you wish.
Here is example from my current project which requires unique field except self.
use Illuminate\Validation\Rule;
$unique_check = Rule::unique('brand_managers', 'email'); // table with some unique rows
//if you need ignore multiple rows/multiple conditions
$unique_check->where(function ($query) use ($brand) {
return $query->whereNotIn('id', $brand->brand_managers->pluck('id')->toArray());
});
$request->validate([
'emails.*' => [ // promocode unique string column
'required',
$unique_check
],
]);
$request->validate([
'name' => ['required', 'string', 'max:255', Rule::unique('brands')->ignore($id)],
'contactNames' => ['required', 'array'],
'contactNames.*' => ['required', 'max:255', 'string', 'distinct',.$brand->id, // ID of record which want to ignore
'emails' => ['required', 'array'],
'emails.*' => ['required', 'max:255', 'email', 'distinct', .$brand->id, // ID of record which want to ignore
'contactNumbers' => ['array'],
'contactNumbers.*' => ['numeric'],
'groupCheckbox' => ['required', 'min:1'],
]);`
pass id want to ignore at time of update records.
more information check https://laravel.com/docs/5.7/validation
hi i have project on laravel 5.6
and this is my role for validation
'voucher_debt' => 'required|array|min:1',
'voucher_debt.*' => 'nullable|numeric|min:0.001',
'voucher_credit' => 'required|array|min:1',
'voucher_credit.*' => 'nullable|numeric|min:0.001',
my problem thats i need it to check if the
array_sum($voucher_credit) - array_sum($voucher_debt) == 0
i tried many thing nothing works out with me
is that possible on laravel
You may do this in your request:
public function rules()
{
$rules = [
'voucher_debt' => ['required', 'array', 'min:1'],
'voucher_debt.*' => ['nullable', 'numeric', 'min:0.001'],
'voucher_credit' => ['required', 'array', 'min:1'],
'voucher_credit.*' => ['nullable', 'numeric' ,'min:0.001'],
];
if (array_sum($this->get('voucher_debt')) - array_sum($this->get('voucher_debt')) == 0) {
throw new ConflictHttpException('YOUR_MESSAGE');
}
}
Or you can make your custom validation rule and add to voucher_debt key
https://laravel.com/docs/5.6/validation#custom-validation-rules