Validate a single variable or an array in Laravel - laravel

I want to validate a single variable like this $name = "example name" but I didn't a way to handle it then I decided to convert it to an array like this $nameArr = ['name' => 'example name'];, the validator is
$rules =
$this->validate($nameArr, [
'name' => 'required|max:10|regex:/^[a-zA-Z0-9]+$/u',
], [
'name.required' => 'name is empty',
'name.max' => 'name must be more less than 10 letters',
'name.regex' => 'invalid name'
]
);
but the Laravel gives this error
Argument 1 passed to App\Http\Controllers\Controller::validate() must be an instance of Illuminate\Http\Request, string given

Correct, the validate function on Controller comes from Illuminate\Foundation\Validation\ValidatesRequests and requires the first paramter to be a request object.
If you want to validate an array, you will have to create the validator manually.
$validator = Validator::make($nameArr,
[
'name' => 'required|max:10|regex:/^[a-zA-Z0-9]+$/u',
],
[
'name.required' => 'name is empty',
'name.max' => 'name must be more less than 10 letters',
'name.regex' => 'invalid name'
]
);
if ($validator->fails()) {
dd($validator->errors());
}

After knowing that the parameter is passed as route url param, I would like to add another option which Laravel provides to validate :
Route::get('user/{name}', 'UserProfileController#getByName')
->where([ 'name' => '[a-z]{10,}' ]);
The where method validates the route param based on provided regular expressions. So [a-z]{10,} will make sure the name is present with 10 or more characters.
See documentation for more

Related

How to validate unique more than one field in Laravel 9?

I want to do validate when store and update data in Laravel 9. My question is how to do that validate unique more than one field?
I want to store data, that is validate formId and kecamatanId only one data stored in database.
For example:
formId: 1
kecamatanId: 1
if user save the same formId and kecamatanId value, its cant saved, and show the validation message.
But if user save:
formId: 1,
kecamatanId: 2
Its will successfully saved.
And then user save again with:
formId: 1,
kecamatanId: 2
It cant saved, because its already saved with the same condition formId and kecamatanId.
My current validate code:
$this->validate($request, [
'formId' => 'required|unique:data_masters',
'kecamatanId' => 'required',
'level' => 'required',
'fieldDatas' => 'required'
]);
Update:
I have try:
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
$formId = $request->formId;
$kecamatanId = $request->kecamatanId;
Validator::make($request, [
'formId' => [
'required',
Rule::unique('data_masters')->where(function ($query) use ($formId, $kecamatanId) {
return $query->where('formId', $formId)->where('kecamatanId', $kecamatanId);
}),
],
]);
But its return error:
Illuminate\Validation\Factory::make(): Argument #1 ($data) must be of type array, Illuminate\Http\Request given, called in /Volumes/project_name/vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php on line 338
You can dry using the different:field rule : which validate that the validated field must be different to the given field;
$this->validate($request,[
'formId' => ['unique:users'],
'kecamatanId' => [
'required',
Rule::unique('users')->where(fn($query) => $query->where('formId', $request->input('formId')))
]
]);

How to make 2 different Laravel Validation messages for the same rule that has 2 different arguments?

Hello I have Laravel validation request with these rules
public function rules()
{
return [
'email' => 'unique:users,email|required|unique:invitations,email',
'name' => 'string|required',
];
}
I want that "unique:users,email" would display one message and "unique:invitations,email" display other message. How to do that?
'unique:users,email' => 'This E-Mail address is already registered.',
'unique:invitations,email' => 'Invitation to this E-Mail address is already sent.',
It always returns default message for "unique" rule.
'unique' => 'The :attribute has already been taken.',
I am not sure if this will work but can you try these
public function messages()
{
return [
'unique:users,email' => 'This E-Mail address is already registered.',
'unique:invitations,email' => 'Invitation to this E-Mail address is already sent.',
//or
'email.unique:users,emai' => 'This E-Mail address is already registered.',
'email.unique:invitations,email' => 'Invitation to this E-Mail address is
//you may even try it without the ,fieldname
'email.unique:users' => ''
];
}
Try to define like
'email.unique:users,emai' => ....,
'email.unique:invitations,emai' => ....,

Handling CodeIgniter form validation (rule keys and data types)

Okay, so I've been searching for a while this question, but couldn't find an answer (or at least some direct one) that explains this to me.
I've been using CodeIgniter 3.x Form Validation library, so I have some data like this:
// Just example data
$input_data = [
'id' => 1,
'logged_in' => TRUE,
'username' => 'alejandroivan'
];
Then, when I want to validate it, I use:
$this->form_validation->set_data($input_data);
$this->form_validation->set_rules([
[
'field' => 'id',
'label' => 'The ID to work on',
'rules' => 'required|min_length[1]|is_natural_no_zero'
],
[
'field' => 'username',
'label' => 'The username',
'rules' => 'required|min_length[1]|alpha_numeric|strtolower'
],
[
'field' => 'logged_in',
'label' => 'The login status of the user',
'rules' => 'required|in_list[0,1]'
]
]);
if ( $this->form_validation->run() === FALSE ) { /* failed */ }
So I have some questions here:
Is the label key really necessary? I'm not using the Form Validation auto-generated error messages in any way, I just want to know if the data passed validation or not. Will something else fail if I just omit it? As this will be a JSON API, I don't really want to print the description of the field, just a static error that I have already defined.
In the username field of my example, will the required rule check length? In other words, is min_length optional in this case? The same question for alpha_numeric... is the empty string considered alpha numeric?
In the logged_in field (which is boolean), how do I check for TRUE or FALSE? Would in_list[0,1] be sufficient? Should I include required too? Is there something like is_boolean?
Thank you in advance.
The "label" key is necessary, but it can be empty.
The "required" rule does not check length, nor does the "alpha_numeric". It checks that a value is present, it does not check the length of said value. For that, there is min_length[] and max_length[].
If you're only passing a 0 or 1, then this is probably the easiest and shortest route.

Laravel Validation custom messages using nested attributes

I would like to ask for some advices about Laravel Validation...
Let's say I've got an input named invoiceAddress[name] and in a controller I've got a rule
$rule = ['invoiceAddress.name' => 'required',];
or just a
$validator = \Validator::make($request->all(), [
'invoiceAddress.name' => 'required',
]);
now, inside custom validation language file validation.php, am I able to nest attributes somehow? like:
'required' => ':attribute is mandatory',
'attributes' => [
'invoiceAddress' => [
'name' => 'blahblah'
],
],
If I try to nest the attribute the way above, i get
ErrorException
mb_strtoupper() expects parameter 1 to be string, array given
because I am using a field (as above)
['name' => 'blahblah']
I am trying to get custom messages using the file and the :attribute directive (as mentioned in the code above).
I am basically trying to do this How to set custom attribute labels for nested inputs in Laravel but i get the mentioned error...
Thank you in advance...
A Note On Nested Attributes
If your HTTP request contains "nested" parameters, you may specify them in your validation rules using "dot" syntax:
$this->validate($request, [
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
]);
Reference: https://laravel.com/docs/5.3/validation#quick-writing-the-validation-logic (A Note On Nested Attributes Section)

Do custom error messages in Laravel 4.2

I'm new in Larvel 4.2 here! How do I do a custom error messages in Laravel 4.2? And where do I put these codes? I've been using the defaults and I kind of wanted to use my own.
Did you try something? http://laravel.com/docs/4.2/validation#custom-error-messages
Did you use Google? Check the documentation (official) it has everything. Be less lazy.
$messages = array(
'required' => 'The :attribute field is required.',
);
$validator = Validator::make($input, $rules, $messages);
To add to the answer given by slick, here is how you could use it in a real example of a store function inside a controller:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'id1' => 'required|between:60,512',
'id2' => 'required|between:60,512',
'id3' => 'required|unique:table',
], [
'id1.required' => 'The first field is empty!',
'id2.required' => 'The second field is empty!',
'id3.required' => 'The third field is empty!',
'id1.between' => 'The first field must be between :min - :max characters long.',
'id2.between' => 'The second answer must be between :min - :max characters long.',
'id3.unique' => 'The third field must be unique in the table.',
]);
if ($validator->fails()) {
return Redirect::back()
->withErrors($validator)
->withInput();
}
//... Do something like store the data entered in to the form
}
Where the id should be the ID of the field in the form you want to validate.
You can check out all the rules you can use here.

Resources