Add maxlength to 255 chars on TextInput by default
For all my TextInput fields, I want to set a default maximum length of 255 characters, which is the commonly used VARCHAR length for database fields.
I tried implementing this in
app/Providers/AppServiceProvider.php
:
However, I encountered an issue: if the TextInput is numeric or decimal, validation fails when the number exceeds 255.
So, I attempted to conditionally apply the maxLength only if the input is not numeric or decimal:
But this approach doesn’t work because configureUsing is called before the component is used in the code, so inputMode is always empty.
What should i do?Solution:Jump to solution
What you likely need to do is to provide a closure to
maxLength()
and only in that closure call getInputMode()
.
You need to imagine that ::configureUsing()
is called immediately when someone does TextInput::make()
. So at that point, if you call getInputMode()
then the code in the configureUsing does not yet know what other methods are chained after it, so hence it doesn't work (what you also said).
The solution therefore would be to fetch the getInputMode()
at run-time, when the getMaxLength() function is actually being called:
```php...4 Replies
You need to pick what you want.... it's that simple.
Either set it as default 255 then override it on each TextInput you want to allow 255 or not. Or on the inputs you want to limit to 255 you limit it, it's that simple.
so if i understand u right, u mean to pick what i want, meaning one of this 2 options:
if my project has 200 inputs type text, i have to say to them ->maxLength(255)?
or if my project has 200 numeric inputs i have to say for all of them maxLength(null)?
if u mean this, i think its not a great idea. i wanted to do it this way to not repeat code and forget about the 255 max char limit. must be better ways, i keep searching
Solution
What you likely need to do is to provide a closure to
maxLength()
and only in that closure call getInputMode()
.
You need to imagine that ::configureUsing()
is called immediately when someone does TextInput::make()
. So at that point, if you call getInputMode()
then the code in the configureUsing does not yet know what other methods are chained after it, so hence it doesn't work (what you also said).
The solution therefore would be to fetch the getInputMode()
at run-time, when the getMaxLength() function is actually being called:
@ralphjsmit 🚀 thanks
thanks toeknee too for the feedback