Validation on custom array - Lumen - php

How can I perform validation on custom array in Lumen framework. e.g:
Example array:
$params = array('name' => 'john', 'gender' => 'male');
I have tried something like this but didn;t work:
$validator = Validator::make($params, [
'name' => 'required',
'gender' => 'required'
]);
if ($validator->fails()) {
$messages = $validator->errors();
$message = $messages->first();
echo $message;
exit;
}

The validation is passing because the fields are in fact present. Use something like min or maxor size to validate the length of a string.
http://lumen.laravel.com/docs/validation#rule-required
Edit
I stand corrected. The required does actually seem to validate if it contains anything.
Update
To clarify; the code that is supposed to run if $validator->fails() doesn't ever run if the validation passes.

Related

Laravel Validation rules: required_without

I have two fields: Email and Telephone
i want to create a validation where one of two fields are required and if one or both fields are set, it should be the correct Format.
I tried this, but it doesnt work, i need both though
public static array $createValidationRules = [
'email' => 'required_without:telephone|email:rfc',
'telephone' => 'required_without:email|numeric|regex:/^\d{5,15}$/',
];
It is correct that both fields produce the required_without error message if both are empty. This error message clearly says that the field must be filled if the other is not. You may change the message if needed:
$messages = [
'email.required_without' => 'foo',
'telephone.required_without' => 'bar',
];
However, you must add the nullable rule, so the format rules don't apply when the field is empty:
$rules = [
'email' => ['required_without:telephone', 'nullable', 'email:rfc'],
'telephone' => ['required_without:email', 'nullable', 'numeric', 'regex:/^\d{5,15}$/'],
];
Furthermore: It is recommended writing the rules as array, especially when using regex.

how to change the key of validation error in laravel

I am new to laravel and working on apis, I have made an api in which i have implemented validation.Everything is working fine but i am stuck on a little thing. I want to to change the key name in the validation error. For example For the "unique" validation error. This is what now showing
I want to rename "email"(text) key with "message"(text)
I have tried so many thing in illuminate/support/validation.php
messagebag.php file but if it changes then error show of "data undefined".
The links i followed are
https://stillat.com/blog/2018/04/21/laravel-5-message-bags-adding-messages-to-the-message-bag-with-add
https://laracasts.com/discuss/channels/laravel/custom-validation-message-for-array-using-different-key?page=0
Override laravel validation message
This is the validation code
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'fcm_token' => 'required',
'password' => 'required',
'c_password' => 'required|same:password'
]);
You can manually loop over the error MessageBag and construct the response to replace a key
$validator = Validator::make($request->all(), [
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required|email|unique:users',
'fcm_token' => 'required',
'password' => 'required',
'c_password' => 'required|same:password'
]);
$errors = [];
foreach ($validator->errors()->messages() as $key => $value) {
if($key == 'email')
$key = 'message';
$errors[$key] = is_array($value) ? implode(',', $value) : $value;
//implode is for when you have multiple errors for a same key
//like email should valid as well as unique
}
$result = array("status" => count($errors)?0:1, 'data'=>$errors);
return $result;
In resources - lang - en (Or Any Langauge) - validation.php
Put This code in bottom:
'attributes' => [
'email' => 'The Email',
],
In order to change the key of the error message of a certain field, you can transfer the validation of this particular field from the request to the controller (or service). This way you can throw an error with any name you want.
For example:
if (#your validation of the field failed#) {
throw ValidationException::withMessages(['your_key' => 'your message']);
}
And don't forget this line:
use Illuminate\Validation\ValidationException;
The error now will look like this:
{
"message": "The given data was invalid.",
"errors": {
"your_key": [
"your message"
]
}
}
if I understand the problem well. This will help you:
a https://laravel.com/docs/7.x/validation#rule-unique
In your case:
'email' => 'required|email|unique:users,message'
unique:table,column,except,idColumn
Hope it helps.
In Laravel, you can try and validate your email this way:
'email'=>'required|email'

Adding a check for validator if field is not empty

I have a validator for users to update their profile, and on the same page the user can change their password. Although, I do not want to run a check if all the 3 fields (current password, new / confirmed) is empty.
Is there a way I can add in a custom check in the Validator::makeand check, or add to the validator and add the return with errors page?
$validator = Validator::make($request->all(), [
'first_name' => 'required|max:191',
'last_name' => 'required|max:191',
'email' => 'required|email|max:191'
]);
example 3 field are empty and wouldnt be a problem, although what if they're filled out... can I append to this for check
example
if ($request->new_password) {
$validator .= array('new_password' => 'required');
}
my last solution would be to have two validators... would that work?
You can accomplish this by adding sometimes to your rule list. sometimes runs validation checks against a field only if that field is present in the input array. As an exmaple,
$v = Validator::make($data, [
'email' => 'sometimes|required|email',
]);
For more rules options you can refer to Laravel Validator Documentation.

Laravel Validator fails due to array to string conversion

I'm trying to validate this input:
$values = [
'id' => $input['id'][$i],
'template_id' => $input['template_id'][$i],
'schedulable_id' => $id,
'schedulable_type' => $type,
'order_by' => $i
];
Against these rules found in my Schedule class:
public static $rules = [
'template_id' => 'required|integer|exists:templates,id',
'schedulable_id' => 'required|integer',
'schedulable_type' => 'required|in:Item,Order',
'order_by' => 'integer'
];
When I do the following, I always get an array to string conversion error in "/laravel/vendor/laravel/framework/src/Illuminate/Validation/Validator.php" on line 905:
$validator = Validator::make($values, Schedule::$rules);
if ($validator->fails()) {
$errors[$i] = $validator->messages();
continue;
}
Why would this be happening?
Just discovered I had Ardent's $forceEntityHydrationFromInput = true and my input cannot be pulled directly from Input for validation purposes due to the fact that it is submitted as an array of partially referenced values.
To fix this, change to $forceEntityHydrationFromInput = false and use standard input validation procedure instead of relying on Ardent's magic.
Sometimes clever packages are too clever.

Laravel if field required, don't return error for each value?

I have a very large registration form.
'username_c' => 'required|unique:contacts_cstm',
'password' => 'required|min:6',
'email' => 'required|email',
'password_repeat' => 'required|same:password',
'first_name' => 'required',
'last_name' => 'required',
'rsa' => 'required',
And so on (another 15 fields)...
The problem is if the form is submitted with nothing entered, about 20 different errors are returned (as they should be).
Except, it would be nice if any of the required fields is NOT entered, to spit back one error saying "All fields are required" or something similar.
I've read through Laravel's docs. on this and didn't find anything. Is there any easy way to do this?
Assuming that all of your fields in the $rules array are required, you should be able to do something as simple as an array_filter($required_fields_input), compare the length against that of your $required_rules and redirect back with a single error message/alert.
See code example below. I tried to keep it simple/commented enough...
Not tested at all ... but theoretically! .... ;)
class YourController {
// ...
public function postFormData()
{
$rules = [
// ...
'first_name' => 'required',
'last_name' => 'required',
'rsa' => 'required'
// ...
];
// Assuming all fields in $rules are "required"
$required_fields = array_keys($rules);
$required_fields_input = Input::only($required_fields);
// Clean out all empty/null fields
$input_not_empty = array_filter($required_fields_input);
if (count($input_not_empty) < count($required_fields))
{
$fill_them_all_in_message = "Please fill in all required fields.";
return Redirect::back()->withMessage($fill_them_all_in_message);
}
/**
* All required fields present
* Continue as usual ..
* .. Validate/Respond/etc...
*/
}
//...
}
I think that pretty much covers your main concern of
a.) Avoiding 15 messages that say "XYZ field is required" ....
b.) Still allowing for the rest of the validation/processing to continue as usual.
Hope that helps!

Categories