In Laravel 5.7 I am using form request validation:
public function rules()
{
return [
'age' => 'integer',
'title' => 'string|max:50'
];
}
If I submit a request to my API with this payload:
{
"age": 24,
"title": ""
}
Laravel returns the error:
{
"message": "The given data was invalid.",
"errors": {
"title": [
"The title must be a string."
]
}
}
I would expect it to pass the validation, since the title is a string, albeit an empty one. How should the validation be formulated to allow empty strings?
The is_null() function checks whether a variable is NULL or not. This function returns true (1) if the variable is NULL, otherwise it returns false/nothing.
you can easily use bail validation in laravel 6, laravel 7, and laravel 8. If you added more than one validation on your field like required, integer, min and max then if the first is fail then the other should stop to display an error message. right now by default, it prints others too.
Laravel's built-in validation rules each have an error message that is located in your application's lang/en/validation.php file. Within this file, you will find a translation entry for each validation rule. You are free to change or modify these messages based on the needs of your application.
You would need nullable
to allow an empty string
public function rules()
{
return [
'age' => 'integer',
'title' => 'nullable|string|max:50'
];
}
Try to see if ConvertEmptyStringsToNull
middleware is active then it would explain this behavior, see docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With