TrimStrings like laravel API does before validating values #4047
joelharkes
started this conversation in
Ideas
Replies: 1 comment 2 replies
-
I actually figured i could use a trait for this and use /**
* Can be used in combination with {@see WithValidation} to trim all strings before validation the Excel files.
* This helps to prevent validation errors due to whitespace in the Excel file.
* see: https://docs.laravel-excel.com/3.1/imports/validation.html#prepare-data-for-validation.
*/
trait TrimStringsForImport
{
public function prepareForValidation(array $data, int $index): array
{
foreach ($data as $key => $value) {
if (is_string($value)) {
$data[$key] = $this->clean($value);
}
}
return $data;
}
private function clean(string $value): ?string
{
/**
* copied from: {@see TrimStrings::transform()}
* to work identically as cleaning incoming https requests.
*/
$cleaned = preg_replace('~(^[\s\x{FEFF}\x{200B}]+)|([\s\x{FEFF}\x{200B}]+$)~u', '', $value) ?? trim($value);
if (empty($cleaned)) {
// make sure empty strings are still converted to null.
return null;
}
return $cleaned;
}
} |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hi,
When using laravel API there is a MiddleWare called TrimStrings which turns empty strings into null and removes whitespace characters from all the strings before Validation is triggered.
Why? for example an email with whitespace in front or back is seen as invalid. by trimming this in advance it leads to much nicer user experience.
Laravel-Excel doesn't do this as far as i could see. leading to inconsistent behaviour between uploading files and filling forms in a Laravel application.
Suggestion: Allow option that TrimsStrings when doing an ->import() which cleans up the data before calling
rules()
Beta Was this translation helpful? Give feedback.
All reactions