J. Doe
J. Doe

Reputation: 999

How to have non-required validation rules in Laravel?

I'm trying to do some form validations in Laravel 5.8,

But even on the fields that don't have the required rule, it throws error...

for example:

request()->validate([
    'username' => ['required','alpha_num','max:40'],
    'email'   => ['email','max:100'],
]);

If I leave the email field "empty" (it is not required) on the form it fails to submit and shows this error: The email must be a valid email address.

I don't understand, why is this happening? and what is the use of required rule when this is the behavior of Laravel validation?

Coming from CodeIgniter community, this is confusing.

Should I also include nullable rule in fields that can be empty?

Upvotes: 2

Views: 2932

Answers (1)

Ragdata
Ragdata

Reputation: 1186

Yes, you should include nullable in fields that can be empty.

It's something that I found a little tricky when I first used Symphony (upon which Laravel is based). If you add a validation rule to a field, the validation rule does not allow for a null value unless the field is also marked as nullable.

The reason you're getting the reported error is because you're forcing the email field to pass the email validation rules - which, of course, it doesn't if left empty.

Upvotes: 6

Related Questions