Validate a field: required_if the url contains parameter in Laravel - php

Is there any way to validate required field when the requested url contains some parameter?

Assuming you are using Form requsts, you can simple use PHP condition.
public function rules()
{
$rules = []; // here you put some rules
// here you check condition and add some rule when it's true
if (str_contains($this->input('url'), 'something')) {
$rules['some_other_field'] = 'required';
}
return $rules;
}

You need to first check the route before validating....
$roles =[
'title' => 'required|unique:posts|max:255',
'author.name' => 'required',
'author.description' => 'required',
];
if(Route::getCurrentRoute()->getPath() == "xxxxx"){
$role['desc'] = 'required'
}
if(\Request::route()->getName() == "yyyy"){
$role['desc'] = 'required'
}
if($request->is('admin/*')){
$role['desc'] = 'required'
}
$this->validate($request, $role);

Related

Laravel - Avoid validation error for unique rule when updating

I'm using Laravel 5.3's validation as follows:
In my model:
public static $validation = [
'name' => 'required',
'username' => 'required|alpha|unique:companies',
'email' => 'required|email|unique:companies',
];
In my controller, I post to the same CompanyController#dataPost method when creating a new item or when editing one:
public function dataPost(Request $request) {
// First validation
$this->validate($request, Company::$validation);
$id = $request->id;
if ($id > 0) {
// Is an edit!
$company = Company::find($id);
$company->update($request->all());
$company->save();
Session::flash('messageclass', 'success');
Session::flash('message', trans('companies.editedsuccessfully'));
} else {
// Is a create
$company = new Company($request->all());
$company->save();
Session::flash('messageclass', 'success');
Session::flash('message', trans('companies.createdsuccessfully'));
}
return redirect()->route('companyindex');
}
The unique validation works ok when I create a new item, but causes an error (as in it flags the username as already existing) when editing an item.
Any idea how to avoid this? Even in an edit I'd still want to ensure the data is unique if it's changed, but if the value is the same as before then ignore the validation.
I know I could do this manually, but I wonder if there is a built-in way to avoid this.
Thanks!
I think you can try this:
public static $validation = [
'name' => 'required',
'email' => Auth::check()
? 'required|email|unique:companies,email,'.Auth::id()
: 'required|email|unique:companies,email',
'username' => Auth::check()
? 'required|alpha|unique:companies,username,'.Auth::id()
: 'required|alpha|unique:companies,username',
];
Hope this work for you !!!
You can update email field with unique property as well.
Following rule will check uniqueness among all emails in other column except current one.
Try this one,
'email' => 'required|unique:users,email,' . $userId
here $userId refers to id of user currently updated.
You can see official docs here
You can create different validation methods for insert or update
public static $validation_update = [
'name' => 'required',
'username' => 'required|alpha',
'email' => 'required|email',
];
public static $validation_add = [
'name' => 'required',
'username' => 'required|alpha|unique:companies',
'email' => 'required|email|unique:companies',
];
Then apply validation in condition
public function dataPost(Request $request) {
// First validation
$id = $request->id;
if ($id > 0) {
// Is an edit!
$this->validate($request, Company::$validation_update);
$company = Company::find($id);
$company->update($request->all());
$company->save();
Session::flash('messageclass', 'success');
Session::flash('message', trans('companies.editedsuccessfully'));
} else {
// Is a create
$this->validate($request, Company::$validation_add);
$company = new Company($request->all());
$company->save();
Session::flash('messageclass', 'success');
Session::flash('message', trans('companies.createdsuccessfully'));
}
return redirect()->route('companyindex');
}
$id = $request->id;
if ($id > 0) {
// Is an edit!
$this->validate($request, Company::$validation_update);
$company = Company::find($id);
$company->update($request->all());
$company->save();

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}$/'
]);
}

Laravel validation OR

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);
});

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.

How do I validate if array is empty?

I have a form with 5 multiple-choice dropdown lists. When submitted, I am trying to run some validation to check that at least one item has been checked.
The code in my controller;
$input = Request::except('postcode_id'); //all user input from the form
$validator = \Validator::make(
[
$input => 'required'
]
);
if ($validator->fails())
{
print "failed";
}else{
print "passed";
}
The error I get is; Illegal offset type. I think I might need to do a custom validator but would like to check first in case there is an easier way.
The first argument of Validator::make() is the data, and the second is an array of validation rules, which are indexed by the input names. You can use required_without_all to validate that at least one must be present, but it is a little verbose:
$validator = \Validator::make($input, [
'dropdown_1' => 'required_without_all:dropdown_2,dropdown_3,dropdown_4,dropdown_5'
'dropdown_2' => 'required_without_all:dropdown_1,dropdown_3,dropdown_4,dropdown_5'
'dropdown_3' => 'required_without_all:dropdown_1,dropdown_2,dropdown_4,dropdown_5'
'dropdown_4' => 'required_without_all:dropdown_1,dropdown_2,dropdown_4,dropdown_5'
'dropdown_5' => 'required_without_all:dropdown_1,dropdown_2,dropdown_3,dropdown_4'
]);
Or write some code to generate the $rules array:
$fields = ['dropdown_1', 'dropdown_2', 'dropdown_3', 'dropdown_4', 'dropdown_5'];
$rules = [];
foreach ($fields as $i => $field) {
$rules[$field] = 'required_without_all:' . implode(',', array_except($fields, $i));
}
$validator = \Validator::make($input, $rules);
You need to use strings in your validator, not variables. Try this instead.
$validator = \Validator::make(
[
'input' => 'required'
]
);
Custom validator itself is not too difficult. I am using it all the time for array input validation. In Laravel 5 Request I will do something like that
public function __construct() {
Validator::extend("pcc", function($attribute, $value, $parameters) {
$rules = [
'container_id' => 'exists:containers,id'
];
foreach ($value as $containerId) {
$data = [
'container_id' => $containerId
];
$validator = Validator::make($data, $rules);
if ($validator->fails()) {
return false;
}
}
return true;
});
}
public function rules() {
return [
'containers' => 'required|pcc',
];
}

Categories