Laravel validation OR - php

I have some validation that requires a url or a route to be there but not both.
$this->validate($request, [
'name' => 'required|max:255',
'url' => 'required_without_all:route|url',
'route' => 'required_without_all:url|route',
'parent_items'=> 'sometimes|required|integer'
]);
I have tried using required_without and required_without_all however they both get past the validation and I am not sure why.
route is a rule in the route field

I think you are looking for required_if:
The field under validation must be present if the anotherfield field is equal to any value.
So, the validation rule would be:
$this->validate($request, [
'name' => 'required|max:255',
'url' => 'required_if:route,""',
'route' => 'required_if:url,""',
'parent_items'=> 'sometimes|required|integer'
]);

I think the easiest way would be creation your own validation rule. It could looks like.
Validator::extend('empty_if', function($attribute, $value, $parameters, Illuminate\Validation\Validator $validator) {
$fields = $validator->getData(); //data passed to your validator
foreach($parameters as $param) {
$excludeValue = array_get($fields, $param, false);
if($excludeValue) { //if exclude value is present validation not passed
return false;
}
}
return true;
});
And use it
$this->validate($request, [
'name' => 'required|max:255',
'url' => 'empty_if:route|url',
'route' => 'empty_if:url|route',
'parent_items'=> 'sometimes|required|integer'
]);
P.S. Don't forget to register this in your provider.
Edit
Add custom message
1) Add message
2) Add replacer
Validator::replacer('empty_if', function($message, $attribute, $rule, $parameters){
$replace = [$attribute, $parameters[0]];
//message is: The field :attribute cannot be filled if :other is also filled
return str_replace([':attribute', ':other'], $replace, $message);
});

Related

Return error response if a body params is not mentionned in the validator

I'm using the Laravel Validator to test my incoming request. So to be sure that the request contains an username and an email, I write something like that:
$validator = Validator::make($request->all(), [
'username' => 'required',
'email' => 'required|email'
]);
if ($validator->fails()) {
return response()->json('error', 400);
};
But if in my request I have an additionnal params like name, the validator will not consider it as an error and will not fail.
Have you an idea how I can make my validator more strict so that the request body match exactly?
Technically it's not a validation fail in the Validator. But you could check if there are extra (unexpected) fields and send a JSON response based on that if you wanted.
Something like this maybe?
$validationRules = [
'username' => 'required',
'email' => 'required|email'
];
$validator = Validator::make($request->all(), $validationRules);
// Check if there are extra (unexpected) fields and fail in that case
$extraFields = $request->except(array_keys($validationRules));
if (count($extraFields) > 0) {
return response()->json('error because there are extra fields', 400);
}
if ($validator->fails()) {
return response()->json('error', 400);
}
return response()->json('ok', 200);
I hope it can help you.
Validation rules can be attached only to properties, so I don't think Laravel's Validator is able to do that. But you still can explicitly forbid certain fields by providing a custom closure rule to them, like this:
$denied = function($attr, $value, $fail) {
$fail("{$attr} is denied.");
};
$validator = Validator::make($request->all(), [
'username' => 'required',
'email' => 'required|email',
'name' => $denied,
'password' => $denied
]);
Otherwise you need to implement custom validation logic, probably utilizing the rule array from your validator as a white list.

Call to a member function fails() on array on laravel

Iam just trying to validate some POST datas.
Route::post('/', function(){
$data = ['url' => request('url')];
$validation = Validator::make($data, ['url' => 'required|url'])->validate();
if($validation->fails())
{
$dd('failed');
}
I don't understand why It doesn't work, can you help me please ?
The error you're getting is due to the return type of ->validate(). This will return an array, so $validation will be an array instead of a Validator instance, and you can't call ->fails() on an array. To solve this, simply omit ->validate():
$validation = Validator::make($data, ['url' => 'required|url']);
if($validation->fails()){
dd("Failed");
}
Sidenote; watch your syntax. $dd() is not a valid call.
You may use the validate method provided by the Illuminate\Http\Request object directly as follow
$request->validate([
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
]);
//if fails code after this line will not be executed
This validation will auto redirected to back.This was default validation by laravel. If it not fails,it will continue with executing.
Manually
Now you can implement manually and redirect as your requirment.
use Validator;
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
//checks your validation and redirect as you want
if ($validator->fails()) {
return redirect('where/ever/you/want')
->withErrors($validator)
->withInput();
}
Again you can default redirection,by calling validate() method
Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
])->validate();
If you call validate method it will redirect as default laravel.
dd() is a method,short version of die and dump
Useful link:
https://github.com/laravel/framework/blob/5.7/src/Illuminate/Validation/Validator.php#L312

validate on array parameter igoners my rules and update

I have a function that updates the data. It receives the data as an array parameter.
I tried use validator make, and also validate helper method but it didn't work because it's only work for requests, and i tried also in validator make as the code below and also 'params.name' but it didn't work.
public function updateCompany(array $params): bool
{
if( Validator::make($params,[
'name'=> 'required|min:3|unique:company',
'email'=> 'required|min:4|unique:company|email'
])) {
return $this->update($params);
}
}
After trying this it didn't give me any error put it ignores my validation rules and update anyway.
Just use
public function updateCompany(Request $request)
then you could do something like this:
$rules = array('name' => 'required',
'email' => 'email|required|unique:users',
'name' => 'required|min:6|max:20');
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
return ['status' => 422, 'errors' => $validator->errors()];
}

Laravel custom validation rule

How can i make a custom validation rule to an input which value must be an integer and starting with 120?
I already read about making custom messages but didnt understand about rules.
I want to use a regex to validate the data. ^120\d{11}$ here is my regex.
I'm new in Laravel that's why cant now imagine how to do that.
A custom validation to use it in $this->validate($request, []);
Now i'm validating data like so:
$this->validate($request, [
'user_id' => 'integer|required',
'buy_date' => 'date',
'guarantee' => 'required|unique:client_devices|number',
'sn_imei' => 'required|unique:client_devices',
'type_id' => 'integer|required',
'brand_id' => 'integer|required',
'model' => 'required'
]);
The input that i want to add custom validation is guarantee
The quickest neatest way is an inline validator in your controller action:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'number' => [
'regex' => '/^120\d{11}$/'
],
]);
if ($validator->fails()) {
return redirect('post/create')
->withErrors($validator)
->withInput();
}
return view('welcome');
}
Where number is the name of the field being submitted in the request.
If you have a lot of validation to do, you might want to consider using a Form Request instead, as a way of consolidating a lot of validation logic.
You can create custom validations in your controller as:
$name = Input::get('field-name')
$infoValidation = Validator::make(
array( // Input array
'name' => $name,
),
array( // rules array
'name' => array("regex:/^120\d{11}$"),
),
array( // Custom messages array
'name.regex' => 'Your message here',
)
); // End of validation
$error = array();
if ($infoValidation->fails())
{
$errors = $infoValidation->errors()->toArray();
if(count($errors) > 0)
{
if(isset($errors['name'])){
$response['errCode'] = 1;
$response['errMsg'] = $errors['name'][0];
}
}
return response()->json(['errMsg'=>$response['errMsg'],'errCode'=>$response['errCode']]);
}
Hope this helps.
Since Laravel 5.5, you can make the validation directly on the request object.
public function store(Request $request)
{
$request->validate([
'guarantee' => 'regex:/^120\d{11}$/'
]);
}

How to validate an Input Array field in Laravel 5.1?

How can I write rule for input field like below:
{!! Form::number("amount[]",null,['min' => 0, 'class' => 'form-control col-xs-2 ']) !!}
I tried following which gave error: htmlentities() expects parameter 1 to be string, array given
$rules = array(
'amount[]' => 'required'
);
$this->validate($request, $rules);
Update:
I tried this as suggested by a user, it's not redirecting it on page again. Below is controller method:
public function postEstimate(Request $request) {
$rules = array(
'amount' => 'required|array'
);
$this->validate($request, $rules);
}
I guess you got issues with what I explained so this is what I meant -
$rules = [];
$count_amounts = count($request->input('amount'));
foreach (range(0, $count_amounts) as $number) {
$rules['amount.' . $number] = 'required|integer|min:0';
}
This should check that each amount input you have is an integer and is bigger than 0 (like you defined in the html validation)
Instead try this:
private $rules = array(
'amount' => 'required|array',
);
public function postEstimate(Request $request) {
$this->validate($request, $this->rules);
}
or, try a validation with a 'amount' => 'required
im not sure about this 'amount' => 'required|array
For custom rules implementation of integer type value check of an array
firstly open the following file
/resources/lang/en/validation.php
Then add the custom message
'numericarray' => 'The :attribute must be numeric array value.',
'requiredarray' => 'The :attribute must required all element.',
Again open the another file
/app/Providers/AppServiceProvider.php
Now add custom validation code in the boot function.
public function boot()
{
$this->app['validator']->extend('numericarray', function ($attribute, $value, $parameters)
{
foreach ($value as $v) {
if (!is_int($v)) {
return false;
}
}
return true;
});
$this->app['validator']->extend('requiredarray', function ($attribute, $value, $parameters)
{
foreach ($value as $v) {
if(empty($v)){
return false;
}
}
return true;
});
}
Now you can use the requiredarray for all element required of array. And also use the numericarray for integer type value check of array
$this->validate($request, [
'field_name1' => 'requiredarray',
'field_name2' => 'numericarray'
]);
if you expect amount as an array the rules should be
$rules = array(
'amount' => 'required|array'
);
check the doc
If your not redirecting or getting a validation error means there is no validation error
just dd($request->input('amount')) in the controller and check its a array or not if it's a array then validations will pass.

Categories