Compare a form input with a regex expression - php

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

Related

Laravel validation rules are not applying properly

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',
...
]);

Laravel: Validation alpha and regex pattern on update

Hello all this is my update controller for an user. I want to know how can I apply these laravel validation rules ONLY to updated fields. Currently when I update only the first name, mobile number also get validated. My name fields are alpha validated and phone number is validated via regex.
public function update(Request $request, User $setting)
{
request()->validate([
'name' => ['required', 'alpha','min:2', 'max:255'],
'last_name' => ['required', 'alpha','min:2', 'max:255'],
'mobile'=>['required', 'string','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.''],
]);
$setting->update($request->all());
return Redirect::back()->with('success','User updated successfully');
}
I able to handle the email(unique) field, but not the others.
Considering the small chat we had in the comments, what you must do is to first get the model from the database and to diff the request with the model's attributes. Then you can keep the validation rules for the changed attributes only.
public function update(int $id, Request $request, User $userRepository)
{
$user = $userRepository->find($id);
$changedAttributes = array_diff($request->all(), $user->getAttributes());
$validationRules = array_intersect_key([
'name' => ['required', 'alpha','min:2', 'max:255'],
'last_name' => ['required', 'alpha','min:2', 'max:255'],
'mobile' => ['required', 'string', '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.''],
], $changedAttributes);
$this->validate($request, $validationRules);
$user->update($changedAttributes);
return Redirect::back()->with('success','User updated successfully');
}

Apply laravel validation rule to all fields at once

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

Check uniqueness of two columns in two tables using validator in Laravel

I am taking input of a field named "email", and checking it using laravel validator. The problem is I want to make sure that the "email" data should be unique in two columns in two different tables. (Sellers and Buyers must not have the same email in their "email" column).
I am able to check the input from one table and column, How should I check the input in both columns? Below is my code.
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'emailOrNumber' => ['required', 'string','email','max:255','unique:usersNew,email'],
'password' => ['required', 'string', 'min:8'],
]);
The above code check email only in usersNew table and in email column, How can I check both tables in here?
You can use the unique rule twice. Once for each table you need to check a field for uniqueness:
'email' => [..., 'unique:table1', 'unique:table2'],
When you don't pass a column to the unique rule it will use the current field name being validated, email in this example.
Laravel 6.x Docs - Validation - Rules - unique
just use it
'email' => 'unique:table1,your_column_name|unique:table2:your_column_name_2'
or use it answer https://laracasts.com/discuss/channels/laravel/validate-a-field-from-2-tables-with-different-message
Try this one,
return Validator::make($data, [
'email' => ['required', 'string','email','max:255','unique:user|unique:email'],
'password' => ['required', 'string', 'min:9'],
]);
In this code unique:username|unique:email will assume the email and username as unique
use below code
return Validator::make($data, [
'name' => ['required', 'string', 'max:255'],
'emailOrNumber' => ['required', 'string','email','max:255','unique:usersNew|unique:email'],
'password' => ['required', 'string', 'min:8'],
]);
Hope it will help you

Laravel Validating An Array in Update Method With Multiple Rows Needing Ignoring

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

Categories