-
Notifications
You must be signed in to change notification settings - Fork 0
Validation
- The
date_format:Y-m-d H:i:s
validator will consider invalid a date time that does not exist due to Day Light Saving Time
Example: When the clock is forwarded in the spring by 1 h, 2025-03-30 02:00:00 will become 2025-03-30 03:00:00 so the interval 2025-03-30 02:00:00...2025-03-30 02:59:59 will not exist in that local timezone date_default_timezone_set('Europe/Amsterdam');
Original report https://github.com/laravel/framework/issues/56760
- The validation for fields that are not required (because they have a default value in DB) but when present in the request, they should be validated works in Maravel (see https://github.com/laravel/framework/issues/41734#issuecomment-3127680521):
'currency' => 'in:EUR,USD',
This will validate (starting with version 10.50.10 of the kernel) the currency when present in the request as empty string and mark it invalid.
sometimes can be used with required. Used alone will have no effect.
Validator::validate(['t'=> null, 'tt' => ''], [
't' => 'sometimes|nullable|in:1',
'tt' => 'sometimes|in:1',
]);
//or
Validator::validate(['t'=> null, 'tt' => ''], [
't' => 'nullable|in:1',
'tt' => 'in:1',
]);
will result in
{
"message": "The given data was invalid.",
"errors": {
"tt": [
"The selected tt is invalid."
]
}
}
To handle update/create with empty string and also handle API requests from HTML forms that come as empty string when not required and not filled/selected, a middleware can be used to retry the request $next($request)
when validation errors occur but after those (if empty) fields are unset from the request. See this issue https://github.com/laravel/framework/issues/56618.
An example with maravel-rest-wizard / laravel-crud-wizard-free (decorated):
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class HandleEmptyStringsOnUpdateAndCreateWhenNeeded
{
public function handle(Request $request, Closure $next): mixed
{
if (
!\in_array($method = $request->getRealMethod(), ['PUT', 'POST'], true)
|| ($method === 'POST' && \str_ends_with($request->getPathInfo(), '/l/i/s/t'))
|| $request->header('Accept', 'application/json') !== 'application/json'
) {
return $next($request);
}
$originalRequest = $request->all();
$firstResponse = $next($request);
if (
!$firstResponse instanceof JsonResponse
|| \str_starts_with((string)(($data = $firstResponse->getData(true))['code'] ?? '4'), '2')
) {
return $firstResponse;
}
foreach (($data['data'] ?? []) as $column => $errorsList) {
if (\is_string($originalRequest[$column] ?? null) && \trim($originalRequest[$column]) === '') {
unset($originalRequest[$column]);
$repeat = true;
}
}
return ($repeat ?? false) ? $next($request->forceReplace($originalRequest)) : $firstResponse;
}
}