Faced the problem while using Laravel 4 validation. Here's the code:
$validator = Validator::make(
array(
'surname' => ['Laravel'],
),
array(
'surname' => 'integer|alpha_dash'
)
);
$validator->passes();
var_dump($validator->failed());
It causes error: Error: preg_match() expects parameter 2 to be string, array given
Lets suppose surname comes from user and it can be array or string.
I have two questions:
Why alpha_dash causes error instead of normal validation error?
Why validation continues to 'alpha_dash' rule after we got FALSE on 'integer' rule? Is this a bug?
What I just did to test arrays:
Created some fields the way you are doing:
<input type="text" name="user[surname][0]">
<input type="text" name="user[surname][1]">
And validated one of them:
$validator = \Validator::make(
Input::all(),
array('user.surname.0' => 'required|min:5')
);
var_dump($validator->passes());
Then I just did it manually:
$validator = \Validator::make(
array(
'user' => ['surname' => [ 0 => 'Laravel'] ],
),
array('user.surname.0' => 'required|min:5')
);
And it worked on both for me.
If you need to analyse something Laravel doesn't provide, you can extend the Validator by doing:
Validator::extend('foo', function($attribute, $value, $parameters)
{
return $value == 'foo';
});
EDIT
But, yeah, there is a bug on it, if you do:
$validator = \Validator::make(
array(
'user' => ['surname' => [ 0 => 'Laravel'] ],
),
array('user.surname.0' => 'integer|alpha_dash')
);
It will give you a
"Error: preg_match() expects parameter 2 to be string, array given".
Here's the Laravel issue posted by the OP: https://github.com/laravel/laravel/issues/2457.
Related
A newbie here in terms of Laravel validation - I've searched and checked the manual but can't seem to find an answer to this. I'm using Laravel 8.0.
As per the Laravel manual I have created a manual validation to validate my array, it contains data similar to the below:
$row = array('John','Doe','john.doe#acme.com','Manager');
Because the array has no keys, I can't work out how to reference the array items using their index when creating the Validator, I've tried this:
$validatedRow = Validator::make($row, ['0' => 'required|max:2', '1' => 'required']);
$validatedRow = Validator::make($row, [0 => 'required|max:2', 1 => 'required']);
$validatedRow = Validator::make($row, [$row[0] => 'required|max:2', $row[0] => 'required']);
But no luck - does anyone have any suggestions?
Use Validator
use Illuminate\Support\Facades\Validator;
Then Update your code
$row = array('John','Doe','john.doe#acme.com','Manager');
$rule = [
'0' => 'required|string',
'1' => 'required',
'2' => 'required|email',
'3' => 'required'
];
$validator = Validator::make($row, $rule);
if ($validator->fails()) {
return response()->json(['errors' => $validator->errors()->all()], 422);
}else{
echo 'ok';
}
I'm trying the laravel validator but getting the error in the title.
This is the part of my code:
What i'm doing wrong?
$data = Validator::make($request->all(),[
'number_1' => Rule::requiredIf(!$request->number_2 && !$request->number_3),
'number_2' => Rule::requiredIf(!$request->number_1 && !$request->number_3),
'number_3' => Rule::requiredIf(!$request->number_1 && !$request->number_2),
]);
I need those three numbers to be at least one required.
You can try this
$data = Validator::make($request->all(),[
'number_1' => 'required_without_all:number_2,number_3',
'number_2' => 'required_without_all:number_1,number_3',
'number_3' => 'required_without_all:number_1,number_3',
]);
Check this link for more info https://laravel.com/docs/8.x/validation#rule-required-without-all
I'm trying to do alphanumeric with spaces validation in CakePHP 3.5.13.
So I've added the following to one of my Table classes:
// src/Model/Table/SavedSearchesTable.php
public function validationDefault(Validator $validator)
{
$validator->add('search_name', [
'alphanumeric' => [
'rule' => ['custom', '/^[a-z0-9 ]*$/i'],
'message' => 'Alphanumeric characters with spaces only'
]
]);
return $validator;
}
This does exactly what I want - I get a validation error message if I enter a string that contains characters other than A-Z, 0-9 or a space.
However...reading about Using Custom Validation Rules in the documentation all of the ->add() calls use 3 parameters.
I've looked into the source (vendor/cakephp/cakephp/src/Validation/Validator.php) and the method looks like this:
public function add($field, $name, $rule = [])
{
// ...
}
How can my rule work if I've passed an array for the second parameter, which it's treating as $name?
Edit : Someone has mentioned in the comments that there is a fallback for older code. Well, if I try and use 3 parameters (instead of 2) in the Model (note addition of 'custom' as second param):
$validator->add('search_name', 'custom', [
'alphanumeric' => [
'rule' => ['custom', '/^[a-z0-9\' ]*$/i'],
'message' => 'Alphanumeric characters with spaces only'
]
]);
It now produces an error:
Unable to call method "" in "default" provider for field "search_name"
The correct answer to this was provided by #ndm in the comments.
I'm writing out a full example in case anyone else has this problem.
It can either be written as:
$validator->add(
'search_name',
'alphanumeric',
[
'rule' => ['custom', '/^[a-z0-9 ]*$/i'],
'message' => 'Alphanumeric characters with spaces only'
]
);
or:
$validator->add('search_name',
[ // second argument is an array. This was how it was in the original question.
'alphanumeric' =>
[
'rule' => ['custom', '/^[a-z0-9 ]*$/i'],
'message' => 'Alphanumeric characters with spaces only'
]
]
);
The following is given as a comment in Cake's source code regarding how the add() method works:
Adds a new rule to a field's rule set. If second argument is an array then rules list for the field will be replaced with second argument and third argument will be ignored.
Both of these have been tested and give the same result in CakePHP 3.5.13
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.
I was trying form validation in laravel.
I have a input text field in my form called 'Category' and i'm given the field name as 'cat' as short.
And i defined the validation rules like this.
public static $rules=array(
"name"=>"required|min:3",
"cat"=>"required"
);
When the validation fails i'm getting error message like this
The name field is required.
The cat field is required.
But i want to display it as "The category field is required" instead of 'cat'. How can i change 'cat' to 'Category' in error message ?.
You can specify custom error message for your field as follows.
$messages = array(
'cat.required' => 'The category field is required.',
);
$validator = Validator::make($input, $rules, $messages);
Please see Custom Error Messages section in laravel documentation for more information.
Or you can keep a mapping for your field names like below. And you can set those into you validator. So you can see descriptive name instead of real field name.
$attributeNames = array(
'name' => 'Name',
'cat' => 'Category',
);
$validator = Validator::make ( Input::all (), $rules );
$validator->setAttributeNames($attributeNames);
you can customize every message ,also change the attribute fields name in validation.php (resources/lang/en/).
for set the attribute in validation.php
'attributes' => [
'name' => 'Name',
'cat' => 'Category',
'field_name'=>'your attribute'
],
I'm using this to deal with dynamic row addition in forms. This answer is provided in context of managing larger forms.
This answer is for Laravel 5
Form request
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Response;
class SomeThingFormRequest extends Request {
public function authorize()
{
//be nice
}
public function rules()
{
//my loop building an array of rules ex: $rules['thing.attribute.'.$x]
}
public function attributes()
{
return [
'thing.attribute'.$x => 'Nice Name',
];
}
Hope this help steer you in the right direction if you are using Laravel 5. I'm currently working on testing it out. The documentation seems to be amiss regarding this potential?
I did some digging in the framework (Illuminate\Foundation\Http\FormRequest.php) and (Illuminate\Validation\Validator.php) for the clues.
Here is an Alternative
$this->validate(request(), [rules], [custom messages], [Custom attribute name]);
$this->validate(request(), [
'fname' => "required|alpha_dash|max:20",
'lname' => "required|alpha_dash|max:30",
'extensionName' => "required|alpha_dash|max:20",
'specialization' => "max:100",
'subSpecialization' => "max:100"
], [],
[
'fname' => 'First Name',
'lname' => 'Last Name',
'extensionName' => 'Extension Name',
'specialization'=> 'Specialization',
'subSpecialization'=> 'Sub Specialization'
]);
Simply got to resources/lang/en/validation.php
There is a blank array named attributes.
add your attribute name here like 'cat'=>'category'
now all validation messages show category instead of cat.
Here's an alternative:
$data = ['name' => e(Input::get('name')), 'cat' => e(Input::get('cat'))];
$rules = ['name' => 'required|min:3', 'cat' => 'required'];
// pass an item from lang array if you need to
$nice_input_names = ['cat' => trans('lang_file.a_name_for_the_category_input')];
$validator = Validator::make($data, $rules, $messages, $nice_input_names);
I think this will do it:
Validator::make($request->all(), [
"name" => "required|min:3",
"cat" => "required"
], [], [
"cat" => "category"
])->validate();
in Laravel 8 this is the Best Way to Customize Validation Attributes and Message;
$request->validate([
'cat' => "required| min:7 |max:15"
//validation Area
],
[
//customize Message
],
[
'cat' => 'Category'
//Customize Attributes Name
]);
the answer by Paul Dela Vega is big help for me, cant comment because no reputation enough.
no information of it anywhere in Laravel Docs (8.x).
maybe this is a good suggestion to laravel, to add this into their documents because it helps a lot for the beginner like me.