Laravel validation for field if "image/file" is selected? - php

I have a field "image", type is file and need only to validate if image is selected, means it can be also empty.
I tried it so: 'avatar' => 'mimes:jpeg,jpg,png,gif|max:100000', but so it is also required.
I tried still with parameters present and sometimes but the field is still required.
How can I validate it only if image is selected?

If the "avatar" field may not be present in the input array you want to use:
'avatar' => 'sometimes|mimes:jpeg,jpg,png,gif|max:100000'
In some situations, you may wish to run validation checks against a field only if that field is present in the input array. To quickly accomplish this, add the sometimes rule.
If the "avatar" field will absolutely be in the input array and it's value will be then null you want to use:
'avatar' => 'nullable|mimes:jpeg,jpg,png,gif|max:100000'
The field under validation may be null. This is particularly useful when validating primitive such as strings and integers that can contain null values. To quickly accomplish this, add the nullable rule.

In your case, You have to check only if it is present or not null - Validating When there is value. So use sometimes
"In some situations, you may wish to run validation checks against a
field only if that field is present in the input array. To quickly
accomplish this, add the sometimes rule to your rule list"
$v = Validator::make($data, array(
'email' => 'sometimes|required|email',
));
In your case,
$v = Validator::make($data, array(
'avatar' => 'sometimes|mimes:jpeg,jpg,png,gif|max:100000',
));
Note:
The following code will do nothing because there are no rules to validate against, done because even if it's present in the POST array, you should specify rules. and the doesn't make any difference.
$v = Validator::make($data, array(
'avatar' => 'sometimes',
));

You could try 'nullable' in your rules.
https://laravel.com/docs/5.3/validation#rule-nullable

First check the $request object. Check avatar is available or not in your request. Then try this:
'avatar' => 'sometimes|image|mimes:jpeg,bmp,png,gif|max:2048'

the solution i found that works best is using Rule::requiredIf
'cover' => [
'image',
Rule::requiredIf(function () {
if (some_condition) {
return false;
}
return true;
})
]

Related

Multiple ignore-fields for is_unique-function

I'm having some issues with the Codeigniter 4 validation rules. I'm using the is_unique function within the ruleset in Order to except one single row from the validation.
The problem here is that there are two fields in the table that need to be checked:
'episodeTitle' => [
'label' => 'episodeTitle',
'rules' => 'required|max_length[100]|is_unique[episodes.episodeTitle,episodes.episodeID,' . $episodeID . ',episodes.podcastID,' . $podcastID . ']',
'errors' => [
'required' => lang('Errors.nested.episode.episodeTitleRequired'),
'max_length' => lang('Errors.nested.messages.maxLength100'),
'is_unique' => lang('Errors.nested.episode.episodeTitleUnique'),
],
],
Is it possible, to make the exception depending on 2 or more fields?
I want to check the episodeID AND the podcastID not only one of these values.
You need to create a custom rule to achieve what you're looking for.
Rules are stored within simple, namespaced classes. They can be stored any location you would like, as long as the autoloader can find it. These files are called RuleSets. To add a new RuleSet, edit Config/Validation.php and add the new file to the $ruleSets array:
public $ruleSets = [
\CodeIgniter\Validation\Rules::class,
\CodeIgniter\Validation\FileRules::class,
\CodeIgniter\Validation\CreditCardRules::class,
];
Within the file itself, each method is a rule and must accept a string as the first parameter, and must return a boolean true or false value signifying true if it passed the test or false if it did not:
class MyRules
{
public function check_unique(string $str): bool
{
// Your code to check the values and don't forget to return true or false.
}
}
Then in your validation just use the check_unique rule.

Laravel: How can I validate two optional date fields using the before and after validation rules

I'm trying to validate the date fields so that active_from needs to be a date before active_until and active_until needs to be a date after active_from.
Both fields are hidden and disabled until the user selects Yes on a select field called active.
When the user selects Yes, the active_from appears and becomes required and the active_until also appears but it's optional and here lies my problem because the validation fails whenever the active_until is not filled.
From what I've understood, if the field may or may not be enabled/exists I should use the sometimes rule which will only check the other validations if the field exists and is enabled. For e.g.
'active_from' => 'sometimes|required_if:active,yes|date|before:active_until',
The nullable rule should be used if a field may or may not be filled but should it also be used if the field may or may not exist? For e.g.
'active_until' => 'sometimes|nullable|date|after:active_from',
So my question is how can I check if active_from is before active_until only if active is selected to Yes and only if active_until is filled.
Am I using the rules correctly, should active_from only be using the sometimes rule or should it also be using the nullable rule?
Code:
$validated = $request->validate([
'title' => 'required|string|min:3|max:30|unique:categories',
'description' => 'nullable|string|min:3|max:255',
'active' => 'required|in:yes,no',
'active_from' => 'sometimes|required_if:active,yes|date|before:active_until',
'active_until' => 'sometimes|nullable|date|after:active_from',
'highlighted' => 'sometimes|required_if:active,yes|in:yes,no',
'highlighted_from' => 'sometimes|required_if:highlighted,yes|date|before:highlighted_until',
'highlighted_until' => 'sometimes|nullable|date|after:highlighted_from',
]);
I was able to finally figure it out.
This is my fixed code:
$validated = $request->validate([
'title' => 'required|string|min:3|max:30|unique:categories',
'description' => 'nullable|string|min:3|max:255',
'active' => 'required|in:yes,no',
'active_from' => 'required_if:active,yes|date',
'active_until' => 'nullable|date|after:active_from',
'highlighted' => 'required_if:active,yes|in:yes,no',
'highlighted_from' => 'required_if:highlighted,yes|date',
'highlighted_until' => 'nullable|date|after:highlighted_from',
]);
Instead of checking both dates being that one is optional even if the user selects Yes on the active select, I just need to check the active_until date (the optional one) to see if it is a valid date after the active_from date.
This way, even if the user doesn't fill the active_until date, the validation won't fail because I have the nullable rule on that field.
As for the sometimes rule, from what I've understood it only needs to be used if a field may or may not exist in the request for e.g.
'active' => 'sometimes|required|in:yes,no',
This way, it's only required if it's present in the request but since I'm using the required_if on my code, it's not necessary because it depends on the value of the other field.
For complex validaion rules
use Illuminate\Support\Facades\Validator;
....
$data = $request->all();
$validator = Validator::make($data,[
//...your unconditional rules goes here
]);
//your conditional rules goes here
$validator->sometimes('active_form', 'before:active_until', function ($request) {
return $request->filled('active_until');//if here return true,rules will apply
});
Important link
conditionally-adding-rules
retrieving-input

Laravel 5.2 - validation - One of the fields is required

Take a scenario,
There are 2 fields available in the form.
1) input type file for manual upload.
2) input type = text to enter youtube video url.
is it possible using laravel built-in validations so that validation will be fired if user has left both fields empty!
I have gone through https://laravel.com/docs/5.3/validation but could not find what I wanted.
In your controller, you could do something like this:
$validator = Validator::make($request->all(), [
'link_upload' => 'required|etc|...',
]);
$validator2 = Validator::make($request->all(), [
'file_upload' => 'required|etc|...',
]);
if ($validator->fails() && $validator2->fails()) {
// return with errors
}
Try required-without-all validation rule. As given in documentation:
The field under validation must be present only when the all of the other specified fields are not present.
Assuming your fields name are url and file, your rule would be like below:
$rules = [
'url' => 'required_without_all:file',
'file' => 'required_without_all:url'
];
required_without:foo,bar,...
The field under validation must be present and not empty only when any of the other specified fields are not present.
Try this,
In youre update method add this
$this->validate($request, [
'fileName'=>'required',
'urlName'=>'required'
]);
dont forget to set the fillable in your model
protected $fillable = ['fileName','urlName'];
Hope this helps

cakephp3 custom validation

I have a duration field that sometimes can be empty and sometimes can't, depending on the other data sent by the form. So I'm trying to do custom validation in CakePHP3.
In my table I did
public function validationDefault(Validator $validator)
{
$validator
->add('duration', 'durationOk', [
'rule' => 'isDurationOk',
'message' => 'duration is not OK',
'provider' => 'table'
]);
return $validator;
}
public function isDurationOk($value, $context)
{
// do some logic
return false; // Always return false, just for test
}
Now when I set the value for duration field I get an 'duration is not OK' error (as expected). But when I let the value empty I get a 'This field cannot be left empty' error.
So I added:
->allowEmpty('duration');
But in this case when duration is empty I don't get an error at all.
Am I doing something wrong or it's just me don't understanding how validation works?
Let me read the book for you:
Conditional Validation
When defining validation rules, you can use the on key to define when
a validation rule should be applied. If left undefined, the rule will
always be applied. Other valid values are create and update. Using one
of these values will make the rule apply to only create or update
operations.
Additionally, you can provide a callable function that will determine
whether or not a particular rule should be applied:
'on' => function ($context) {
// Do your "other data" checks here
return !empty($context['data']['other_data']);
}
So just define the conditions depending on your "other data" in the callback to apply the rule only when the conditons are true.
Alternatively you can manipulate the plain form data even before it gets validated in the beforeMarshal() callback of the table and change the form data as needed or load another validator or modify the validator.

Laravel rule for unique excluding blank or null

I have a user model that needs to have unique email addresses but I also want to allow them to be left blank in case the user has no email...I see in docs there is a way to make a rule for unique and an exception for an id...but I'm not sure how to make this allow null or blank but unique if it is not. Sorry seems like this is simple but I can't think of the answer.
public static $adminrules =
'email' => 'email|unique:users,email,null,id,email,NOT_EMPTY'
);
Edit It may be that using the rule without required is enough since a blank or null would pass validation in those cases. I might have a related bug that making it so I can't add more than 1 blank email, so I can't verify this.
public static $adminrules =
'email' => 'email|unique:users'
);
I tried this. Adding 'nullable' before 'sometimes'.
$validator = Validator::make($request->all(), [
'email' => 'nullable|sometimes|unique:users',
]);
You should try this:
$v->sometimes('email', 'email|unique:users,email', function($input)
{
return !empty($input->email);
});
$v is your validator object and you basically say that in case the email field is not empty it should also be unique (there shouldn't be a users table record with this value in email column).
In your Requests/UserRequest you'd have something like
public function rules()
{
return [
'email' => [
'nullable',Rule::unique((new User)->getTable())->ignore($this->route()->user->id ?? null)
]
];
}
The usage of nullable is what allows the field to be nullable. The other part is to check if the email is unique in the User model table.
If you wish to validate if the field is unique
between two fields please refer to this answer.
in another table, then add the following to your rules
'exists:'.(new ModelName)->getTable().',id'
You should try to change your structure of database to make the field email is nullable. And in the rules try this :
$this->validate($request,
[
'email' => 'email',
]
);
if(isset($request->address))
{
$this->validate($request,
[
'email' => 'email|unique:users'
]
);
}

Categories