0
I have the following validator cpfValidacao.php
:
<?php
namespace App\Utils;
class cpfValidacao
{
public function validate($attribute, $value, $parameters, $validator)
{
return $this->isValidate($attribute, $value);
}
protected function isValidate($attribute, $value)
{
$c = preg_replace('/\D/', '', $value);
if (strlen($c) != 11 || preg_match("/^{$c[0]}{11}$/", $c)) {
return false;
}
for ($s = 10, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--);
if ($c[9] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
return false;
}
for ($s = 11, $n = 0, $i = 0; $s >= 2; $n += $c[$i++] * $s--);
if ($c[10] != ((($n %= 11) < 2) ? 0 : 11 - $n)) {
return false;
}
return true;
}
}
Call on the AppServiceProvider.php
:
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
Validator::extend('cpf', '\App\Utils\cpfValidacao@validate');
}
Call on the controller:
/* validação de parâmetros */
$validator = Validator::make($request->all(), [
'email' => 'required|min:1|max:255',
'cpf' => 'required|min:1|max:11|cpf',
'name' => 'required|min:1|max:255',
'password' => 'required|min:8|max:255'
//'profile_picture_path' => 'required|min:1|max:255'
]);
if($validator->fails()){
$errors = $validator->errors();
return response()->json(['error' => true, $errors], 422);
}
/* fim */
Return:
{
"error": true,
"0": {
"cpf": [
"validation.cpf"
]
}
}
I want to customize the message "validation.cpf"
. How do you do?
Laravel 6.2
The ideal would be to create a Rule even without having to extend the service Provider, there you can define the message you want, https://laravel.com/docs/7.x/validation#custom-validation-Rules
– Thiago
Right thanks brother
– Luiz Roberto Furtuna