How to Validate Form Data in Laravel

Today we are going to learn how to validate form data in Laravel.

When you are submitting a form, you may need to validate data fields to check whether they are clean and meet the certain standards. For example, you may need to validate numeric fields, date and time fields, maximum length of a field and so on.

When you are developing a web application you have to manually validate all these criteria. But Laravel has made our lives so much easier because you can validate form data very easily with Laravel requests.

So let’s get started.

Create a Simple form

Firstly I am creating a simple form.

In this form I am adding the following fields.

  • title
  • description
  • date
  • id


<form action="{{route('YOUR ROUTE HERE')}}" method="post">
   @csrf
   <input type="text" name="title">
   @if ($errors->has('title'))
      {{ $errors->first('title') }}
   @endif

   <textarea name="description"></textarea>
   @if ($errors->has('description'))
      {{ $errors->first('description') }}
   @endif

   <input type="text" name="date">
   @if ($errors->has('date'))
      {{ $errors->first('date') }}
   @endif

   <input type="text" name="id">
   @if ($errors->has('id'))
      {{ $errors->first('id') }}
   @endif

</form>

In the form, below each field, I have put errors array with a condition to display validation error messages of each field. Therefore we can display meaningful validation error messages that makes sense.

Create Request File

Now we need to write the specific request to validate this form on submit. Firstly we need to create a request. For that, type this command and hit enter on the terminal.

 php artisan make:request ValidateForm 

You can use any name for the request. I’m using ValidateForm.

Now open up that file in the request folder and add the following validation rules to the request file.

'title'=>'required|max:20',
'description'=>'required|max:200',
'date'=>'required|date_format:Y-m-d'
'id' => 'required|numeric'

For each validation rule, you can define custom validation messages as well.

'title.required'=>'Please enter Title',
'title.max'=>'Title is too long',
'description.required'=>'Title is too long',
'description.max'=>'Title is too long',
'date.required'=>'Title is too long',
'date.date_format'=>'Title is too long',
'id.required'=>'Title is too long',
'id.numeric'=>'Title is too long',

Make sure you made this request authorized true in order to pass this validation request file.


public function authorize() { 
   return true; 
}

The entire Request file should look like this.

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ValidateForm extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title'=>'required|max:20',
            'description'=>'required|max:20',
            'date'=>'required|max:20',
            'id' => 'required|numeric'
        ];
    }


    public function messages()
    {

        return [
            'title.required'=>'Please enter Title',
            'title.max'=>'Title is too long',
            'description.required'=>'Title is too long',
            'description.max'=>'Title is too long',
            'date.required'=>'Title is too long',
            'date.date_format'=>'Title is too long',
            'id.required'=>'Title is too long',
            'id.numeric'=>'Title is too long',
       ]
    }
}

You can see all the validation rules that level support in the Laravel documentation.

Alright we are done with the request file.

Testing

Now let’s write a simple method in a controller to handle the form data. So that we can check whether our validation request is working.

 public function store(ValidateForm $request) {
       dd($request);
 }

You have to use ValidateForm request type as the argument of this method.

Now fill the form with invalid data and hit enter in order to test the validation request. You may see the form does not submit and it is redirect back with the validation error messages.

Like this, you can validate any type of data with Laravel requests. Therefore you don’t have to write your own validation rules for each and every form and this saves lot of time and effort thanks to Laravel.

That’s it.

 


Food for thought: How to Upload files to S3 with Laravel

Leave a Reply

Your email address will not be published. Required fields are marked *