Adding Form Validation & Displaying Error & Success Messages
Laravel is a popular PHP framework used for building web applications. One common task when building web applications is to create a contact form that allows users to send messages to the site owner.
However, it’s important to validate the form data to ensure that it’s accurate and prevent any errors or malicious attacks. In this tutorial, we’ll show you how to add validations and display error messages in the Laravel contact form that we built in our previous tutorial.
Step 1: Define a Method to Handle the Form Submission
The first step is to define a method in your controller that handles the form submission. In this method, you’ll use the validate() function to validate the form data according to your desired rules.
For example, you can require the name,
email,
subjet
, and message fields to be non-empty and validate the email field to ensure that it’s a valid email address.
And here’s how it is done:
Open the ContactForm.php file in a text editor so that we can edit it. To recall, the ContactForm.php file is located inside Users/Username/livewire_practice/app/Http/Livewire/ContactForm.php.
Once the file is opened in the text editor, add the following lines of code right below to your contact form variables, as shown in the image below:
protected $rules = ([ 'name' => 'required', 'email' => 'required|email', 'subject' => 'required', 'message' => 'required', ]);
The code line that we have added will determine what criteria our input form fields must meet. There are a ton of rules that you can use to validate the input field data but we have used only the “required” rule along with the “email” rule for the email form field, setting that every form field is required to be filled and the email field is specifically required to be filled with a valid email address.
Next, add the following line of code right after the curly bracket opens for the save function:
$this->validate();
The above code is the validation method that will ensure redirecting the user to the same contact form if the entered field data fails to validate.
Step 2: Displaying the Error Messages
Now we have added the Validation and rules to our contact form which will ensure the user enters the correct information inside the contact form fields.
The second step is to display any validation errors to the user. And for that, we are going to use the @error directive to display any validation errors.
The @error directive will check if there are any errors for the given field and display the error message if there are any. Here’s how to do so:
To begin with, open up the contact-form.blade.php file in a text editor, located at /Users/Username/livewire_practice/resources/views/livewire/contact-form.blade.php.
Here, paste the following line of code under each <input> tag as shown below:
@error('model_name') @{{ $message }} @enderror
Make sure to replace “model_name” with the actual model name of the input tag you are pasting the code below. E.g. if you are entering the code under the input tag of the email model, replace “model_name” with “email“.
We are using the @error
directive to check if there are any errors for the name,
email, and
message fields. If there are any errors, they’ll get displayed right below each form field as shown below.
Further, we can style these error messages by using the code below:
@error('model_name') <span class="text-danger">@{{$message}}</span> @enderror
Again make sure to replace “model_name” with the actual model name of their respective input tags.
The above styling will show the severity of the message,i.e., setting the error message color to red.
Step 3: Displaying the Success Message
The next step is to add the success message to the contact form to let the user know that the entered details have been submitted successfully. To do this, follow the below steps.
Open up the ContactForm.php file inside the text editor which should already be opened if you have not closed it after completing step 2.
In the ContactForm.php file, paste the following code right along with the other “Use” statements in a separate line:
use Session;
After that paste the following line of code:
Session::flash('success', 'Your information has been submitted!');
right before
// redirect to form return redirect()->to('/');
This will store the success message temporarily until the next page loads. Then it displays the message and stops storing it.
Lastly, open up the contact-form.blade.php file in the text editor and paste the following code right after the first <div> tag and before the <form> tag:
@if($success) <div> @{{$success}} </div> @endif
And that’s it for adding the success message to the contact form. From now onwards, whenever the user will submit the correct details there will be a success message displayed right on the top of the contact form.
In this tutorial, we’ve shown you how to add validations and display the error and success messages in a Laravel contact form. By using Laravel’s built-in validation functionality, you can ensure that the form data is accurate and prevent any errors or malicious attacks.
By displaying error messages to the user, you can help users understand what they need to do to correct any errors. Finally, by customizing error messages, you can make your contact form more user-friendly and improve the user experience.