Implementing Custom Validation Rules

Tutorial 2 of 5

Introduction

Welcome to this tutorial on creating and implementing custom validation rules in Laravel. Our goal is to explore various scenarios that require more than the built-in validation rules in Laravel and how to handle them.

What You'll Learn
- How to create custom validation rules in Laravel
- How to implement these rules in your application

Prerequisites
- A basic understanding of PHP and Laravel
- Laravel installed on your local machine

Step-by-Step Guide

Understanding Validation

Validation in Laravel is essential to ensure that the correct data type is being sent to your database. Laravel provides a variety of built-in validation rules, but sometimes you may need to specify some custom ones.

Creating a Custom Validation Rule

You can create a custom validation rule using the make:rule Artisan command:

php artisan make:rule YourCustomRule

This command will create a rule object in your app/Rules directory.

Implementing the Custom Rule

To use this custom rule, you will pass it to your validator in the form of an object:

$request->validate([
    'field' => [new YourCustomRule],
]);

Code Examples

Example 1: Custom Rule for String Length

Let's create a custom rule that validates that a string is exactly 5 characters long.

  1. Create the Rule
php artisan make:rule FiveCharactersLong
  1. Define the Rule

In the app/Rules/FiveCharactersLong.php file:

public function passes($attribute, $value)
{
    return strlen($value) === 5;
}
  1. Implement the Rule
$request->validate([
    'username' => [new FiveCharactersLong],
]);

Summary

In this tutorial, we've learned how to create and implement custom validation rules in Laravel. You now know how to create a rule using the make:rule artisan command, define the rule in your app, and implement it in your code.

Next Steps

Experiment with creating different custom validation rules. Try creating a rule that validates if a number is prime or if a string is a palindrome.

Additional Resources

Practice Exercises

  1. Exercise 1: Create a custom validation rule that checks if a number is even.

  2. Exercise 2: Create a custom validation rule that checks if a string contains only alphabets and spaces.

  3. Exercise 3: Implement the custom rules you created in exercises 1 and 2 in a form.

Solutions

  1. Solution to Exercise 1:
public function passes($attribute, $value)
{
    return $value % 2 == 0;
}
  1. Solution to Exercise 2:
public function passes($attribute, $value)
{
    return preg_match('/^[A-Za-z ]*$/', $value);
}

Remember to keep practicing and experimenting with different rules. The more you practice, the better you will understand how to implement and use custom validation rules in Laravel.