0

I have the following validation:

'location.zip_code' => ['required', 'numeric', 'max:99999'],

It's working as expected except if I submit my form with a numeric value preceeded by a space, like 12345. A trailing space gets trimmed via the TrimStrings middleware (presumably), but a leading space doesn't?

This ends up causing this error:

SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'zip_code' at row 1

I know I can change my save method to do something like, $validatedData = $this->validate(); and then handle each form input value, trimming this one in the process, but I've got a lot going on in the form, and it would be great if there was a way for this to just work the way it should work. Hoping someone has an idea.

hyphen
  • 2,368
  • 5
  • 28
  • 59
  • is your `zip_code` field in the database an integer or a string ? if you switch it to integer, you wouldn't have to care about leading space in a numeric field. – N69S Feb 13 '23 at 20:11
  • Why presumably? `TrimString` does `preg_replace('~^[\s​]+|[\s​]+$~u', '', $value) ?? trim($value)`, no need for assumptions, it [removes leading and trailing spaces](https://onlinephp.io/c/e5edb). – dbf Feb 13 '23 at 20:25
  • well, because it's seemingly not removing the leading space, hence what prompted the question. Evidently I've done something that's caused TrimString not to work as I would expect it to work. – hyphen Feb 13 '23 at 22:20
  • 1
    Can you add a `dd` and show us the result wih the space? – matiaslauriti Feb 13 '23 at 22:20
  • I could change the zip code to be numeric, yes, but I'd also like to understand why a leading space isn't trimmed. – hyphen Feb 13 '23 at 22:21

2 Answers2

0

In your database, the column ‘’zip_code’’ change the data type to VarChar or String

HeroCode
  • 13
  • 5
0

I think the correct approach is to modify the zip_code field in my database to be an integer left padded to 5 digits to account for zip codes that start with 0. Similar to this:

https://stackoverflow.com/a/3201014/4113027

hyphen
  • 2,368
  • 5
  • 28
  • 59