Laravel 8 Tutorial - Form Validation

In this video, we are going to learn about form validation in Laravel 8. Form validation is used to ensure that all required form controls are filled out in the correct format.

Now, let's see how we can apply the validation to a form. So, switch to the project. Now, click on the login view. In this view file, you can see the email field and password field.

Let's open this in the browser. So, go to the browser and just type here /login. Now, if I'm not going to provide any validation, then the user can put anything inside the input box. Like, put here "assdf", which is not a valid email address.

Without validation, when I click on the submit button, it will be submitted, which is not good. So, to ensure that all the fields are filled out in the correct format, we use form validation.

Now, I'm going to put the validation with this form. So, go to the LoginController and inside the loginSubmit method, write the following code:


public function loginSubmit(Request $request)
{
$validatedData = $request->validate([
'email' => 'required|email',
'password' => 'required|min:6|max:12'
]);
$email = $request->input('email');
$password = $request->input('password');
return 'Email : '.$email. ' Password : '.$password;
}

Now, go to the login.blade.php view file. Here, let's display the validation error message. So, for that, add the following code after the email and password input field:


@error('email') {{message}} @enderror

@error('password') {{message}} @enderror

Now, save the view and switch to the browser and refresh the page. Now, enter some invalid data and click on submit. You can see here it is showing some validation error.

Error message must be in red color. So, for that, just add a CSS in the head:


<style>
.error{
color:red;
}
</style>

Refresh the page, re-enter the invalid data. Ok, now the error message is showing in red color. Now, we put valid values in both fields and click on submit. Now, you can see here the form has been submitted successfully.

So, in this way, you can add form validation with the form in Laravel 8.