If you want to create a custom validation rule, you can do so for instance in the boot
method of a service provider, via the Validator facade.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
Validator::extend('starts_with', function($attribute, $value, $parameters, $validator) {
return \Illuminate\Support\Str::startsWith($value, $parameters[0]);
});
Validator::replacer('starts_with', function($message, $attribute, $rule, $parameters) {
return str_replace(':needle', $parameters[0], $message);
});
}
}
The extend
method takes a string which will be the name of the rule and a function which in turn will be passed the name of the attribute, the value being validated, an array of the rule parameters, and the validator instance, and should return whether the validation passes. In this example, we are checking if the value string starts with a given substring.
The error message for this custom rule can be set as usual in the /resources/lang/[lang]/validation.php
file, and can contain placeholders, for instance, for parameters values:
'starts_with' => 'The :attribute must start with :needle.'
The replacer
method takes a string which is the name of the rule and a function which in turn will be passed the original message (before replacing), the name of the attribute, the name of the rule, and an array of the rule parameters, and should return the message after replacing the placeholders as needed.
Use this rule as any other:
$this->validate($request, [
'phone_number' => 'required|starts_with:+'
]);