How to Use Form Validation In Laravel?

8 minutes read

Form validation in Laravel is a crucial aspect of ensuring that data submitted by users is accurate, complete, and meets the required criteria. Laravel provides an intuitive way to handle form validation through its powerful validation mechanism.


To use form validation in Laravel, you need to follow these steps:

  1. Define validation rules: Begin by specifying the rules for each form field. Laravel provides a wide range of validation rules such as required, email, numeric, unique, etc. These rules are defined inside the rules method of the controller responsible for handling the form submission.
  2. Create validation messages: Optionally, you can define custom error messages for specific validation rules. Laravel allows you to override default error messages for better user experience and understanding. Messages are typically defined in the messages method of the controller.
  3. Perform validation: Once the validation rules and error messages are defined, you can perform the actual validation. In Laravel, this is done using the validate method, which automatically validates the incoming request data based on defined rules. If any validation errors occur, Laravel will automatically redirect back to the previous page with the error messages.
  4. Display error messages: To display the validation error messages on the form, Laravel provides a convenient way to access and display the errors. You can use the errors variable in your Blade views to retrieve and show the specific error messages for each field.
  5. Customize error messages: If you want to further customize the error messages or display them differently than the default behavior, Laravel allows you to manually retrieve error messages for each field and apply additional formatting or styling.


By following these steps, you can easily implement form validation in Laravel to ensure that the submitted data is valid and meets the specified criteria. This helps in preventing the storage of incorrect or invalid data and enhances the overall user experience.

Best Laravel Frameworks Books to Read in 2024

1
Laravel: Up and Running: A Framework for Building Modern PHP Apps

Rating is 5 out of 5

Laravel: Up and Running: A Framework for Building Modern PHP Apps

2
Beginning Laravel: Build Websites with Laravel 5.8

Rating is 4.9 out of 5

Beginning Laravel: Build Websites with Laravel 5.8

3
Laravel: Up & Running: A Framework for Building Modern PHP Apps

Rating is 4.8 out of 5

Laravel: Up & Running: A Framework for Building Modern PHP Apps

4
Laravel: Up & Running

Rating is 4.7 out of 5

Laravel: Up & Running

5
Practical Laravel: Develop clean MVC web applications

Rating is 4.6 out of 5

Practical Laravel: Develop clean MVC web applications

6
Laravel - Un framework efficace pour développer vos applications PHP

Rating is 4.5 out of 5

Laravel - Un framework efficace pour développer vos applications PHP


How to validate numeric ranges in Laravel forms?

To validate numeric ranges in Laravel forms, you can use the between validation rule. Here's an example of how you can define a validation rule for a numeric range in a Laravel form:

  1. Open the form request file associated with your form. This file is typically located in the app/Http/Requests directory and extends the Illuminate\Foundation\Http\FormRequest class.
  2. Define a validation rule in the rules method of your form request class. Use the between validation rule to specify the acceptable range of numbers.


For example, if you want to validate that a field named amount should be between 10 and 100, you can add the following rule:

1
2
3
4
5
6
public function rules()
{
    return [
        'amount' => 'required|numeric|between:10,100',
    ];
}


  1. Save the form request file.
  2. Laravel will automatically handle the validation based on the defined rules. If the user submits a form with a value outside the specified numeric range, Laravel will return an error message indicating the validation failure.


You can then display the error message in your view file using the @error directive provided by Laravel. Here's an example of how you can display the error message for the amount field:

1
2
3
@error('amount')
    <div class="alert alert-danger">{{ $message }}</div>
@enderror


Note: Make sure to replace amount with the name of the field you want to validate in your form.


How to validate a form in Laravel?

To validate a form in Laravel, you can follow these steps:


Step 1: Create a Form Request Create a new form request class by running the following command:

1
php artisan make:request YourFormRequest


This will generate a new form request class in the "app/Http/Requests" directory.


Step 2: Define Validation Rules Open the generated form request class and define the validation rules in the rules() method. For example:

1
2
3
4
5
6
7
8
public function rules()
{
    return [
        'name' => 'required|string|max:255',
        'email' => 'required|email|unique:users',
        'password' => 'required|string|min:8|confirmed',
    ];
}


Step 3: Handle Failed Validation By default, Laravel automatically handles failed validation by redirecting back with error messages. If you want to customize the response, you can override the failedValidation() method in your form request class. For example:

1
2
3
4
protected function failedValidation(Validator $validator)
{
    throw new HttpResponseException(response()->json(['errors' => $validator->errors()], 422));
}


Step 4: Use the Form Request in Your Controller In your controller method, type-hint the form request class and Laravel will automatically validate the incoming request. If validation fails, it will redirect back or return a JSON response with error messages. For example:

1
2
3
4
5
6
7
use App\Http\Requests\YourFormRequest;

public function store(YourFormRequest $request)
{
    // The form request has already validated the input
    // Perform the necessary operations
}


That's it! Laravel's form request feature will handle the validation for you. If the validation fails, it will automatically send back the appropriate response with error messages.


How to validate nested form fields in Laravel?

To validate nested form fields in Laravel, you can make use of Laravel's "dot notation" syntax in the validation rules. Here's an example of how you can validate nested fields:

  1. Define the rules in your controller or form request class:
1
2
3
4
5
6
7
8
public function rules()
{
    return [
        'nested.field1' => 'required',
        'nested.field2' => 'numeric',
        // add more validation rules for other nested fields
    ];
}


Here, nested.field1 and nested.field2 are examples of nested form fields.

  1. In your form, make sure to use the correct naming convention for the nested fields. For example, if you have an input field for field1 inside a nested nested field, you can name it as nested[field1]:
1
2
3
<input type="text" name="nested[field1]">
<input type="text" name="nested[field2]">
<!-- add more input fields for other nested fields -->


  1. If you're using a form request class for validation, make sure to update the parameter name where necessary:
1
2
3
4
public function store(NestedFormRequest $request)
{
    // ...
}


With this setup, Laravel will automatically handle the validation for the nested form fields and report any validation errors in the same way as it does for non-nested fields.

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

Related Posts:

Form validation in CodeIgniter is a crucial step in ensuring that the data submitted through a form is accurate and secure. CodeIgniter provides a built-in form validation library that simplifies the validation process.To use form validation in CodeIgniter, fo...
In CakePHP, form handling and validation are crucial components when building a web application. Here is an overview of how to implement form handling and validation in CakePHP:Creating a Form: Begin by creating a view file (.ctp) for the form. You can use the...
Form validation in Laravel is a powerful feature that allows developers to easily validate user input and ensure data integrity before saving it to the database.To handle form validation in Laravel, developers can use the built-in validation feature provided b...