GluePear
GluePear

Reputation: 7715

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?

Upvotes: 34

Views: 61595

Answers (6)

Anwar
Anwar

Reputation: 4246

The accepted answer does not fix the issue when you have this rule:

return [
  "title" => "sometimes|string",
];

In this case, you need to specifiy the string is actually "nullable" (even if the ConvertEmptyStringsToNull middleware is active, tested on Laravel 8.77.1)

So this one will allow to pass an empty string on the "title" key:

return [
  "title" => "sometimes|string|nullable",
];

Upvotes: 0

ErcanE
ErcanE

Reputation: 1641

Avoid touching Middleware settings.

Instead Use Laravel build in function to manipulate data before validation runs.

Inside Validation class

protected function prepareForValidation()
    {
        if($this->title == null )
            $this->merge(['title'=>'']);
    }

Upvotes: 1

Mahdi Aslami Khavari
Mahdi Aslami Khavari

Reputation: 1985

there is present rule in that check present of a key but let it to be empty.

#present

present The field under validation must be present in the input data but can be empty.

https://laravel.com/docs/5.7/validation#rule-present

Upvotes: 8

Shuyi
Shuyi

Reputation: 916

I will try

public function rules() 
{
    return [
        'age' => 'integer',
        'title' => 'string|sometimes'
    ];
}

This will only validate title when it is present.

Upvotes: 0

ka_lin
ka_lin

Reputation: 9432

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

Upvotes: 25

Zakalwe
Zakalwe

Reputation: 1613

You would need nullable to allow an empty string

public function rules() 
{
    return [
        'age' => 'integer',
        'title' => 'nullable|string|max:50'
    ];
}

Upvotes: 59

Related Questions