Step 1: Create a Controller for Validation
Use the Artisan command to create a ValidationController:
Step 2: Add Methods in the Controller
Next, in your app/Http/Controllers/ValidationController.php, add the following methods to show the form and handle form validation:
Step 3: Create a View File for the Form
Create the view file resources/views/login.blade.php and add the following code for the login form:
In this view:
-
The validation errors are displayed if any are present using the
$errorsvariable. -
The form contains
usernameandpasswordfields, which are validated in the controller.
Step 4: Define Routes
Define the routes for the validation form and POST request in your routes/web.php file:
Step 5: Test the Validation
Now, visit the following URL in your browser to test the validation:
If you click the "Login" button without entering anything in the fields, you will see error messages like:
-
The username field is required.
-
The password field is required.
This ensures that the form is properly validated before being processed.
Explanation of the Code
-
Validation Rules:
-
In the
validateformmethod, thevalidatemethod is used to validate the form data. Here,'username' => 'required|max:8'checks that the username is required and has a maximum length of 8 characters, and'password' => 'required'checks that the password field is required.
-
-
Error Handling:
-
The errors are displayed in the form if validation fails. In the view, the errors are accessed via the
$errorsvariable, which is an instance ofIlluminate\Support\MessageBag.
-
-
Displaying Error Messages:
-
If there are any validation errors for a specific field (like
usernameorpassword), they are shown below the respective input field.
-
-
CSRF Token:
-
Laravel uses CSRF protection, so you need to include
{{ csrf_field() }}in your form to prevent cross-site request forgery attacks.
-
Conclusion
This example demonstrates how to implement simple form validation in Laravel. By using the validate method, you ensure that user input is validated before processing it, improving the security and reliability of your application.
