How to validate array in Request rules laravel? - laravel

I create request in laravel for validation where i have to validate phone number array.How to validate it. Below i am sharing:
Array that i pass in postman is:
{
"name": "test nbame",
"phone_number": {
"number": "+8896 5432",
"internationalNumber": "+852 7896 5432",
"nationalNumber": "+8896 5432",
"e164Number": "+85278965432",
"countryCode": "HK",
"dialCode": "+852"
},
"designation": "xyz"
}
public function rules()
{
return [
'name' => 'required',
'dial_number' => 'required',
'phone_number' => 'required|regex:/(^[0-9 ]+$)+/',
//'image' => 'required',
];
}
how to validate phone_number array.

Based on your json you can do something like below
public function rules()
{
return [
'name' => 'required',
'dial_number' => 'required',
'phone_number' => 'required|array',
'phone_number.number' => 'required|regex:/(^[0-9 ]+$)+/',
'phone_number.internationalNumber' => 'required|regex:/(^[0-9 ]+$)+/',
'phone_number.nationalNumber' => 'required|regex:/(^[0-9 ]+$)+/',
'phone_number.e164Number' => 'required',
'phone_number.countryCode' => 'required|string',
'phone_number.countryCode' => 'required|string',
'phone_number.dialCode' => 'required',
//'image' => 'required',
];
}
for more info you can visit laravel documentation

You're validating against a nested array in Laravel:
public function rules()
{
return [
...
'phone_number.number' => 'required|regex:/(^[0-9 ]+$)+/',
];
}
Read more in the docs.

You will check the number by regex. You will find a lot of variants of possible phone numbers. That means that you need a regex which is very flexible. How flexible the regex should be depends on you. here is an example:
'phone_number.number' => 'required|regex:/(^[0-9 ]+$)+/',

Related

Laravel validating that key in array is in an array of given strings

I'm building an API that takes in an array of 'additional_data' but I want some control over the fields that can be passed in.
Take the following JSON:
{
"name": "Joe Bloggs",
"additional_data": {
"type": "example",
"other_type": "example"
}
}
My current validation attempt:
return [
'name' => ['required'],
'additional_data.*' => ['sometimes', Rule::in(['type'])]
];
This always fails validation, what I'm looking for is to validate the key of the array so I can make sure the keys passed in are part of a 'whitelist'.
What you do now is you try to validate content of additional_data.type and additional_data.other_type.
You can do this by adding a custom validator. For example
Validator::extend('check_additional_data_keys', function($attribute, $value, $parameters, $validator) {
return is_array($value) && array_diff(array_keys($value), ['type', 'other_type']) === 0);
});
and use it inside your current rules
return [
'name' => ['required'],
'additional_data' => ['check_additional_data_keys'],
'additional_data.*' => ['required', 'string'],
];
Just specify your whitelist keys using the array validation rule:
return [
'name' => 'required',
'additional_data' => [
'sometimes',
'array:type',
],
];
1- In case you want applay same validation on all arrays' keys you can use the following:
return [
'name' => 'required',
'additional_data' => ['array', Rule::in(['type'])]
];
2- In case each key in the array needs different validation use the following:
return [
'name' => 'required',
'additional_data' => 'array',
'additional_data.ky1' => ['your validation here'],
'additional_data.ky2' => ['your validation here'],
];

Laravel make custom error validation messages

Greeting, this is my code and I need to make custom error messages for every rule
$validator = Validator::make($request->all(), [
'name' => 'required|min:3|max:100',
'phone' => 'required',
'date' => 'required',
'address' => 'required|min:3|max:100',
'test' => 'required|min:3|max:100',
]);
if ($validator->fails()) {
$errors = $validator->errors();
return response()->json($errors);
}
Its better to create a separate request for validation purpose
public function rules(): array
{
return [
'name' => 'required|min:3|max:100',
'phone' => 'required',
'date' => 'required',
'address' => 'required|min:3|max:100',
'test' => 'required|min:3|max:100',
]
}
public function messages(): array
{
return [
'name' => 'Please enter name'
];
}
you can create your own custom validation messages in two ways:
1- in resources/lang/en/validation.php you can change the validation message for every rule
2- you can pass your custom message for each validation like this:
$validator = Validator::make($input, $rules, $messages = [
'required' => 'The :attribute field is required.',
]);
you can check here for more information
specific to your question:
$messages = [
'required' => 'The :attribute field is required.',
'min' => ':attribute must be more than 3 chars, less than 100'
]
$validator = Validator::make($request->all(), [
'name' => 'required|min:3|max:100',
'phone' => 'required',
'date' => 'required',
'address' => 'required|min:3|max:100',
'test' => 'required|min:3|max:100',
], $messages);

laravel validate unique fields on update

I am using the L5 repository and it has the validator package (https://github.com/andersao/laravel-validator) but I am have problems to do the validation of the unique fields on update it, anyone to help me???
******the example bellow I tried in this way on RULE_UPDATE but no success..
((((((FIELDS I WANT TO VALIDATE : people_id, email BECAUSE THESE ARE UNIQUE ONLY FOR REST OF THE USERS, NOT TO THIS CURRENT USER THAT ITS UPDATING )))))))
calling the validation in the UserService.php:
use Prettus\Validator\Contracts\ValidatorInterface;
public __construct(){
$this->validator = \App::make('App\Validators\UserValidator');
}
save($data){
if(!empty($data['id'])){
$this->validator->with($data)->passesOrFail(ValidatorInterface::RULE_UPDATE);
}else{
$this->validator->with($data)->passesOrFail(ValidatorInterface::RULE_CREATE);
}
}
namespace App\Validators;
use \Prettus\Validator\Contracts\ValidatorInterface;
use \Prettus\Validator\LaravelValidator;
class UserValidator extends LaravelValidator
{
protected $rules = [
ValidatorInterface::RULE_CREATE => [
'people_id' => 'required|unique:users',
'active' => 'required',
'available_chat' => 'required',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
'masters_id' => 'required',
],
ValidatorInterface::RULE_UPDATE => [
'id' => 'required',
'people_id' => 'required|unique:users,id,:id',
'active' => 'required',
'available_chat' => 'required',
'email' => 'required|string|email|max:255|unique:users,id,:id',
//'password' => 'required|string|min:6|confirmed',
//'masters_id' => 'required',
],
];
protected $messages = [
'id.required' => 'Usuário não encontrado!',
'people_id.required' => 'Pessoa é obrigatório',
'people_id.unique' => 'Pessoa já cadastrada',
'active.required' => 'Obrigatório',
'available_chat.required' => 'Obrigatório',
'email.required' => 'Digite o e-mail',
'password.required' => 'Digite a senha',
'password.min' => 'Digite uma senha com 6 caracteres',
'password.confirmed' => 'Confirme a senha corretamente',
'email.unique' => 'E-mail já cadastrado',
];
}
Try to put the id of the register in method setId
$this->validator->with($data)->setId($id)->passesOrFail(ValidatorInterface::RULE_UPDATE);
While updating you need to force a unique rule to Ignore Given ID
'people_id' => 'required|user,people_id,'.$id
//id is the primary id of the field which you want to update
with unique validation which must be ignored
https://laravel.com/docs/5.2/validation#rule-unique
Try to use the below changes it will work.
Add below code in your Validator for check Unique Email validation
ValidatorInterface::RULE_UPDATE => [
'email' => 'required|unique:customers,email,id'
],
After that set id for validation code like this
$this->validator->with($request->all())->setId($id)->passesOrFail(ValidatorInterface::RULE_UPDATE);

Laravel 5.4 Validation Request , How to handle unique validation on update?

I have a users table which has a unique validate rule on email and username. When i am trying to update not ignore unique validation. Please see my code below.
UserRequest.php
public function rules()
{
return [
'name' => 'required',
'mobile' => 'required',
'email' => 'required|unique:users,email'.$id,
'usercategory' => 'required',
'username' => 'required|unique:users,username'.$id,
];
}
Please try this
public function rules()
{
$id = $this->request->get('id') ? ',' . $this->request->get('id') : '';
return [
'name' => 'required',
'mobile' => 'required',
'email' => 'required|unique:users,email'.$id,
'usercategory' => 'required',
'username' => 'required|unique:users,username'.$id,
];
}
In laravel 5.5 you should do like this:
use Illuminate\Validation\Rule;
Validator::make($data, [
'email' => [
'required',
Rule::unique('users')->ignore($user->id),
],
]);
Check laravel documentaion about rule-unique.
You needed to skip id if you validate for update, like as below
public function rules($id='')
{
$id = $id ? ','.$id.',id':'';
return [
'name' => 'required',
'mobile' => 'required',
'email' => 'required|unique:users,email'.$id,
'usercategory' => 'required',
'username' => 'required|unique:users,username'.$id,
];
}
In Laravel docs, you have provide 3rd and 4th param in unique rule
unique:table,column,except,idColumn
You could use something like this:
$id = $this->isMethod('put') ? ',' . auth()->id() : '';
assuming you use put method for update
before line with return
for somebody else faced this issue:
public function rules()
{
return [
'name' => 'required',
'mobile' => 'required',
'email' => 'required|unique:users,email'.$this->user->id,
'usercategory' => 'required',
'username' => 'required|unique:users,username'.$this->user->id,
];
}
I fixed this by using this:
public function rules()
{
$id = $this->user->id ?? null;
return [
"name" => "required",
"mobile" => "required",
"email" => "required|unique:users,email, $id",
"usercategory" => "required",
"username" => "required|unique:users,username, $id",
];
}
Note that for other models other than the User model, the user in $this->user->id will be the model name in lowercase

Laravel 5 : Form Request based on conditional if

How I can apply conditional if in my rules() method in request something like this code.
public function rules()
{
if($request->field1 = 'something')
{
return [
'field1' => 'required',
'field2' => 'required',
];
}else if($request->field1 = 'other something')
{
return [
'field1' => 'required',
'field2' => 'required',
'field3' => 'required',
'field4' => 'required',
];
}
}
You can use request() helper function, it returns the current request instance or obtains an input item as:
public function rules()
{
if (request('field1') == 'something') {
return [
'field1' => 'required',
'field2' => 'required',
];
} else if (request('field1') == 'other something') {
return [
'field1' => 'required',
'field2' => 'required',
'field3' => 'required',
'field4' => 'required',
];
}
}
The FormRequest object is an instance of the Request, so just use $this to get the value you're looking for:
public function rules()
{
if ($this->field1 == 'something') {
return [
'field1' => 'required',
'field2' => 'required',
];
} else if ($this->field1 == 'other something') {
return [
'field1' => 'required',
'field2' => 'required',
'field3' => 'required',
'field4' => 'required',
];
}
}
Do note however that if field1 is not set to one of those two values (or is missing completely) the code above will not be returning any rules. You have to accomodate for that.
You can use Laravel Build-in Validation Rules Required If OR Required Unless OR Requred With in your case

Resources