2
votes

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?

1
It's because null or an empty string isn't a valid email address. If you want to also accept null, include nullable.lufc

1 Answers

5
votes

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.