'is there any way to validate a field that sometime is File(image) && sometime is String(Src of same image)
my problem : i am using laravel framework php
i want validate a field witch my field sometime is File(image) and sometime is String(src of same image)
is there any shortcut or solution in Laravel ???
Solution 1:[1]
The specifics of your question are not exactly clear but I think you can manage what you want by doing something like:
$request->validate([
'stringOrFile' => [
function ($attribute, $value, $fail) {
if (!is_string($value) && !($value instanceof UploadedFile)) {
$fail('The '.$attribute.' must either be a string or file.');
}
}
]
]);
Where UploadedFile
refers to \Illuminate\Http\UploadedFile
and stringOrFile
refer to the name of the input your are validating.
However if possible use a different name for the input depending on what it is so you can have more complex validation rules on each different input.
More details on these kinds of validation rules in the manual
Solution 2:[2]
Actually while using the form data, empty image is received as a string "null". you can manage this in your controller.
$request->request->add(['image' => $request->image== "null" ? null : $request->image]);
$request->validate(['image'=> nullable|sometimes|image|mimes:jpeg,png,jpg,svg])
or you can send an empty string in case if image is not attached.
Solution 3:[3]
I use this code example. take any part useful for you.
$msg=[
'name.required'=>'<span class="badge">Name</span> is Required',
'username.required'=>'<span class="badge">User Name</span> is Required',
'born.required'=>'<span class="badge">User Name</span> is Required'
];
$request->validate([
'name'=>'required|string|min:2|max:30',
'username'=>'required|string|min:3|max:20',
'born'=>'required|date',
'image'=>'nullable|image|mimes:jpg,jpeg,bmp,png'
],$msg);
$msg for errors
you should create error page blade name error contains
@if($errors->any())
{!! implode('', $errors->all('<div class="alert alert-danger">:message</div>')) !!}
@endif
///
in blade that contain form for validation write top code
@include('error')
include error page if exist any error to display errors
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | apokryfos |
Solution 2 | Muhammad |
Solution 3 | Waad Mawlood |