Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel string validation to allow empty strings

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?

like image 859
GluePear Avatar asked Feb 22 '19 15:02

GluePear


People also ask

How check string is empty in laravel?

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.

What is bail in laravel validation?

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.

How to validate data in Laravel?

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.


2 Answers

You would need nullable to allow an empty string

public function rules() 
{
    return [
        'age' => 'integer',
        'title' => 'nullable|string|max:50'
    ];
}
like image 177
Zakalwe Avatar answered Sep 22 '22 11:09

Zakalwe


Try to see if ConvertEmptyStringsToNull middleware is active then it would explain this behavior, see docs

like image 31
ka_lin Avatar answered Sep 21 '22 11:09

ka_lin