options = $options; } /** * Determine if the validation rule passes. * * @param string $attribute * @param mixed $value * @return bool */ public function passes($attribute, $value) { return self::isValid($value); } public static function isValid($cnpj) { $cnpj = preg_replace('/[^0-9]/', '', (string) $cnpj); // Valida tamanho if (strlen($cnpj) != 14) return false; // Verifica se todos os digitos são iguais if (preg_match('/(\d)\1{13}/', $cnpj)) return false; // Valida primeiro dígito verificador for ($i = 0, $j = 5, $soma = 0; $i < 12; $i++) { $soma += $cnpj[$i] * $j; $j = ($j == 2) ? 9 : $j - 1; } $resto = $soma % 11; if ($cnpj[12] != ($resto < 2 ? 0 : 11 - $resto)) return false; // Valida segundo dígito verificador for ($i = 0, $j = 6, $soma = 0; $i < 13; $i++) { $soma += $cnpj[$i] * $j; $j = ($j == 2) ? 9 : $j - 1; } $resto = $soma % 11; return $cnpj[13] == ($resto < 2 ? 0 : 11 - $resto); } /** * Get the validation error message. * * @return string */ public function message() { if (array_key_exists('message', $this->options)) { return $this->options['message']; } $attribute = array_key_exists('attribute', $this->options) ? $this->options['attribute'] : ':attribute'; return "O campo {$attribute} informado é um CNPJ inválido."; } }