Reputation: 111
I'm trying to create a custom validator in Laravel 5 but got stuck after creating the Resolver. When the validation is called it returns:
FatalErrorException in Factory.php line 97: Call to undefined method dpvnice\Validators\CustomValidator::setPresenceVerifier()
boot function:
use Validator;
use Route;
use dpvnice\Validators\CustomValidator;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider {
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot(){
$messages = ['cnpj' => 'CNPJ inválido', 'cpf' => 'CPF inválido'];
Validator::resolver(function($translator, $data, $rules, $messages){
return new CustomValidator($translator, $data, $rules, $messages);
});
} ...
customValidator class:
<?php namespace dpvnice\Validators;
use Validator;
class CustomValidator extends Validator {
public function validateCpf ($attribute, $cpf, $parameters){
// Verifica se um número foi informado
if(empty($cpf)) {return false;}
// Elimina possivel mascara
$cpf = str_replace(array(".","/","-"),"",$cpf);
// Verifica se o numero de digitos informados é igual a 11
if (strlen($cpf) != 11) {
return false;
}
// Verifica se nenhuma das sequências invalidas abaixo
// foi digitada. Caso afirmativo, retorna falso
else if ($cpf == '00000000000' ||
$cpf == '11111111111' ||
$cpf == '22222222222' ||
$cpf == '33333333333' ||
$cpf == '44444444444' ||
$cpf == '55555555555' ||
$cpf == '66666666666' ||
$cpf == '77777777777' ||
$cpf == '88888888888' ||
$cpf == '99999999999') {
return false;
// Calcula os digitos verificadores para verificar se o
// CPF é válido
} else {
for ($t = 9; $t < 11; $t++) {
for ($d = 0, $c = 0; $c < $t; $c++) {
$d += $cpf{$c} * (($t + 1) - $c);
}
$d = ((10 * $d) % 11) % 10;
if ($cpf{$c} != $d) {
return false;
}
}
return true;
}
}
function validateCnpj ($attribute, $cnpj, $parameters){
...
}
}
Usage on code:
public function postAdicionarConvidado(Request $request){
$input = Input::all();
$v = Validator::make($request->all(), $this->convidadoRules, $this->convidadoRulesMessage);
$v->sometimes('senha', 'required|same:confirmar-senha|min:5', function($input){
return is_null(User::where(['email' => $input['email']])->first());
});
...
Upvotes: 3
Views: 1345
Reputation: 62228
Your custom validator class needs to extend Illuminate\Validation\Validator
, not the alias to the Validator
facade.
<?php namespace dpvnice\Validators;
class CustomValidator extends Illuminate\Validation\Validator {
// code
}
Upvotes: 3