🔧 Programmierung 🕛 vor 11 Monaten 3 Min Lesezeit
0

Laravel 12 Custom Validation Rule with Parameters

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht

Learn how to implement Laravel 12 custom validation rules with parameters in a simple, structured way. This tutorial covers multiple approaches, including Rule objects and Closures, with hands-on examples.






Why Use Custom Validation Rules?



Sometimes Laravel’s built-in validation rules aren’t enough. That’s when custom validation rules come in handy. They are especially useful when:




  • You need to handle complex business logic.

  • Validation depends on multiple fields.

  • You require domain-specific rules that Laravel doesn’t include out of the box.



Custom rules with parameters also help you avoid code duplication by creating a single reusable class. These classes can be adapted for different contexts by passing parameters through the constructor.






Creating Custom Validation Rules with Parameters



Laravel offers two main approaches for building custom validation rules:




  • Using a Closure

  • Using a Rule Object (recommended)



In this guide, we’ll explore both methods to implement parameterized validation rules.






Method 1: Using Rule Objects (Recommended)



The Rule Object approach is the preferred method when you want to reuse validation logic across multiple forms, controllers, or requests.






Step 1: Generate a Custom Rule



Use Artisan to generate a new rule class:




CODE
php artisan make:rule Username







This command creates a new file Username.php inside the App\Rules directory.






Step 2: Update AppRulesUsername.php



Next, open the generated Username.php file and update it with the following code:




CODE
<?php

namespace App\Rules;

use Closure;
use Illuminate\Contracts\Validation\ValidationRule;

class Username implements ValidationRule
{


protected $minLength;
protected $allowSpecialChars;

public function __construct(int $minLength = 3, bool $allowSpecialChars = false)
{
$this->minLength = $minLength;
$this->allowSpecialChars = $allowSpecialChars;

}
/**
* Run the validation rule.
*
* @param \Closure(string, ?string=): \Illuminate\Translation\PotentiallyTranslatedString $fail
*/
public function validate(string $attribute, mixed $value, Closure $fail): void
{
// Check minimum length
if (strlen($value) < $this->minLength) {
$fail("The {$attribute} must be at least {$this->minLength} characters long.");
return;
}

// Check for valid characters
if ($this->allowSpecialChars) {
$pattern = '/^[a-zA-Z_@\-\.]+$/';
} else {
$pattern = '/^[a-zA-Z_]+$/';
}

if (!preg_match($pattern, $value)) {
$fail("The {$attribute} contains invalid characters.");
return;
}
}

}







In Laravel 12, you can implement the validate(string $attribute, mixed $value, Closure $fail) method via the ValidationRule interface, while also accepting constructor parameters for flexible validation policies.



In the following custom rule example, we’ll define two parameters in the constructor:





  • minLength – sets the minimum number of characters required (default: 3).


  • allowSpecialChars – determines whether special characters are permitted (default: false).



Both parameters are optional, so you can use the defaults or override them when applying the rule.



Here’s how the validation logic works:





  • Check minimum length – If the username does not meet the required length, a validation error is returned.


  • Check allowed characters – If allowSpecialChars is true, special characters like @, -, or . are allowed. If allowSpecialChars is false, only letters and underscores are permitted.



This approach makes your validation logic **configurable and reusable **across multiple forms or controllers.



Check out the full step-by-step guide here : Laravel 12 Custom Validation Rule with Parameters

Vollständiger Original-Artikel
Den kompletten Beitrag mit allen Details direkt auf dev.to lesen.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
1 Quelle
How did I not know that Call of Duty: Modern Warfare 3 Zombies was this much fun?
1 Quelle
Here are all the new Xbox games shown at Tokyo Game Show 2026, with updates for titles releasing in 2027 and beyond
1 Quelle
Samsung Galaxy Watch 9 zum Tiefstpreis: Neue Smartwatch fällt überraschend stark im Preis bei Amazon
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Laravel 12 Custom Validation Rule with Parameters

Thematisch verwandte Begriffe: Laravel, Custom, Validation, Rule · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...