[4.x] Support for class-based rules with new “rule:” syntax
Laravel 10 has marked the existing Illuminate\Contracts\Validation\Rule as deprecated, and new rules are created using Illuminate\Contracts\Validation\ValidationRule, which can't be added to Laravel's Validator using the extend method (unless I'm missing something).
This PR adds support for a new syntax for using your own custom rules for Blueprint validation.
You can make your Laravel Rule as per Laravel's docs, such as:
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class MyCustomRule implements ValidationRule
{
public function validate(string $attribute, mixed $value, Closure $fail): void
{
// your rule logic
// call $fail('your error message') when validation fails
}
}
In the YAML or Blueprint editor, you can attach this rule to the validation using the rule: prefix:
validate:
- rule:\App\Rules\MyCustomRule
This also supports rules that have custom parameters:
namespace App\Rules;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
class HasOneDefaultRule implements ValidationRule
{
protected $varA;
protected $varB;
public function __construct($a, $b)
{
$this->varA = $a;
$this->varB = $b;
}
public function validate(string $attribute, mixed $value, Closure $fail): void
{
// your rule logic
}
}
Params are in the key:value syntax, with multiple separated by commas. Such as:
rule:{class}:{keyA}:{valueA},{keyB}:{valueB},{keyC}:{valueC}
rule:\App\Rules\MyCustomRule:varA:valueA,varB:valueB
This will call the MyCustomRule, and pass valueA and valueB as the parameters.
There may be a neater way to handle the parameters but this keeps it as open-ended as possible for the user's rule implementation.