0
0
Laravelframework~5 mins

Available validation rules in Laravel

Choose your learning style9 modes available
Introduction

Validation rules help check if the data users send to your app is correct and safe. They stop mistakes and bad data before saving.

When a user submits a form with their name and email.
When saving a new product with price and description.
When users upload files and you want to check file type and size.
When updating user settings and you want to ensure valid inputs.
When you want to make sure a date is in the future or a number is positive.
Syntax
Laravel
$request->validate([
    'field_name' => 'rule1|rule2|rule3',
]);
Use pipe (|) to separate multiple rules for one field.
Rules can be simple like 'required' or have parameters like 'max:255'.
Examples
This checks that the email field is filled and looks like an email address.
Laravel
$request->validate([
    'email' => 'required|email',
]);
This ensures age is given, is a whole number, and at least 18.
Laravel
$request->validate([
    'age' => 'required|integer|min:18',
]);
This checks password is filled, is text, at least 8 characters, and matches confirmation.
Laravel
$request->validate([
    'password' => 'required|string|min:8|confirmed',
]);
Sample Program

This controller method checks if the name, email, and password meet the rules before saving. It returns a success message if all is good.

Laravel
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    public function store(Request $request)
    {
        $validated = $request->validate([
            'name' => 'required|string|max:50',
            'email' => 'required|email|unique:users,email',
            'password' => 'required|string|min:8|confirmed',
        ]);

        // Imagine saving user here

        return response()->json(['message' => 'User data is valid and saved!']);
    }
}
OutputSuccess
Important Notes

Always validate data before using it to keep your app safe and working well.

You can create custom validation rules if needed for special cases.

Laravel has many built-in rules like 'required', 'email', 'unique', 'min', 'max', and more.

Summary

Validation rules check user input to prevent errors and bad data.

Use pipe-separated rules to combine checks on each field.

Laravel offers many ready-to-use rules and lets you make your own.