Skip to content

Instantly share code, notes, and snippets.

@asllanmaciel
Last active June 14, 2022 13:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asllanmaciel/c8d7840bc8837c5dae83ed11f463ab02 to your computer and use it in GitHub Desktop.
Save asllanmaciel/c8d7840bc8837c5dae83ed11f463ab02 to your computer and use it in GitHub Desktop.
Diversas validações para PHP
<?php
function valida_url_preg($url)
{
if (!preg_match('|^http(s)?://[a-z0-9-]+(\.[a-z0-9-]+)*(:[0-9]+)?(/.*)?$|i', $url)) {
return false;
}
}
function valida_url_filter_var($url)
{
if (!filter_var($url, FILTER_VALIDATE_URL)) {
return false;
}
}
function valida_email($email)
{
$mail_correcto = 0;
//verifico umas coisas
if ((strlen($email) >= 6) && (substr_count($email, "@") == 1) && (substr($email, 0, 1) != "@") && (substr($email, strlen($email) - 1, 1) != "@")) {
if ((!strstr($email, "'")) && (!strstr($email, "\"")) && (!strstr($email, "\\")) && (!strstr($email, "\$")) && (!strstr($email, " "))) {
//vejo se tem caracter .
if (substr_count($email, ".") >= 1) {
//obtenho a terminação do dominio
$term_dom = substr(strrchr($email, '.'), 1);
//verifico que a terminação do dominio seja correcta
if (strlen($term_dom) > 1 && strlen($term_dom) < 5 && (!strstr($term_dom, "@"))) {
//verifico que o de antes do dominio seja correcto
$antes_dom = substr($email, 0, strlen($email) - strlen($term_dom) - 1);
$caracter_ult = substr($antes_dom, strlen($antes_dom) - 1, 1);
if ($caracter_ult != "@" && $caracter_ult != ".") {
$mail_correcto = 1;
return true;
} else {
return false;
}
}
}
}
}
return true;
}
function valida_email_filter($email)
{
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
return false;
}
}
function valida_email_preg($email)
{
$conta = "/[a-zA-Z0-9\._-]+@";
$domino = "[a-zA-Z0-9\._-]+.";
$extensao = "([a-zA-Z]{2,4})$/";
$pattern = $conta . $domino . $extensao;
if (preg_match($pattern, $email))
return true;
else
return false;
}
function valida_nome($nome)
{
if (!preg_match("/^[a-zA-Z-' ]*$/", $nome)) {
return false;
}
}
function valida_hora($hora)
{
$t = explode(":", $hora);
if ($t == "")
return false;
$h = $t[0];
$m = $t[1];
if (!is_numeric($h) || !is_numeric($m))
return false;
if ($h < 0 || $h > 24)
return false;
if ($m < 0 || $m > 59)
return false;
return true;
}
function valida_data($data)
{
$t = explode("/", $data);
if ($t == "")
return false;
$dia = $t[0];
$mes = $t[1];
$ano = $t[2];
if (!is_numeric($dia) || !is_numeric($mes) || !is_numeric($ano))
return false;
if ($dia < 1 || $dia > 31)
return false;
if ($mes < 1 || $mes > 12)
return false;
if ($ano < 1800 || $ano > 2100)
return false;
return true;
}
function valida_data_checkdate($valor)
{
$arraData = explode('/', $valor);
if (checkdate($arraData[1], $arraData[0], $arraData[2])) :
return true;
else :
return false;
endif;
}
function valida_cpf($cpf)
{
// Extrai somente os números
$cpf = preg_replace('/[^0-9]/is', '', $cpf);
// Verifica se foi informado todos os digitos corretamente
if (strlen($cpf) != 11) {
return false;
}
// Verifica se foi informada uma sequência de digitos repetidos. Ex: 111.111.111-11
if (preg_match('/(\d)\1{10}/', $cpf)) {
return false;
}
// Faz o calculo para validar o CPF
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 valida_cnpj($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);
}
function valida_extensao_arquivo($arquivo)
{
$extensoes_aceitas = array('bmp', 'png', 'svg', 'jpeg', 'jpg');
$array_extensoes = explode('.', $arquivo);
$extensao = strtolower(end($array_extensoes));
if (array_search($extensao, $extensoes_aceitas) === false) :
return true;
else :
return false;
endif;
}
function valida_cep($cep)
{
if (preg_match('/[0-9]{5,5}([-]?[0-9]{3})?$/', $cep)) :
return true;
else :
return false;
endif;
}
function valida_telefone($telefone)
{
if (preg_match('/^\([0-9]{2}\)?\s?[0-9]{4,5}-[0-9]{4}$/', $telefone)) :
return true;
else :
return false;
endif;
}
function valida_telefone_2($telefone)
{
$regex = '/^(?:(?:\+|00)?(55)\s?)?(?:\(?([1-9][0-9])\)?\s?)?(?:((?:9\d|[2-9])\d{3})\-?(\d{4}))$/';
if (preg_match($regex, $telefone) == false) {
return false;
} else {
return true;
}
}
function valida_telefone_3($telefone)
{
$regex = '/^(?:(?:\+|00)?(55)\s?)?(?:\(?([1-9][0-9])\)?\s?)?(?:((?:9\d|[2-9])\d{3})\-?(\d{4}))$/';
if (preg_match($regex, $telefone) == false) {
return false;
} else {
return true;
}
}
function valida_telefone_3_ddd($telefone)
{
$regex = '/^(?:(?#DDI)(?:\+|00)?(55)\s?)?(?:(?#DDD)\(?([1-9][0-9])\)?\s?)(?:(?#Telefone)((?:9\d|[2-9])\d{3})\-?(\d{4}))$/';
if (preg_match($regex, $telefone) == false) {
return false;
} else {
return true;
}
}
function valida_celular($telefone)
{
$telefone = trim(str_replace('/', '', str_replace(' ', '', str_replace('-', '', str_replace(')', '', str_replace('(', '', $telefone))))));
$regexTelefone = "^[0-9]{11}$";
// Regex para validar somente celular
$regexCel = '/[0-9]{2}[6789][0-9]{3,4}[0-9]{4}/';
if (preg_match($regexCel, $telefone)) {
return true;
} else {
return false;
}
}
function valida_ip($ip)
{
if (!preg_match("^([0-9]){1,3}.([0-9]){1,3}.([0-9]){1,3}.([0-9]){1,3}$", $ip)) {
return false;
}
}
/**
* Valida vários tipos de elementos
*
* @param mixed $var
* @param mixed $type
* @return boolean
*/
function valida_itens($var, $type)
{
if (array_key_exists($type, self::$regexes)) {
$returnval = filter_var($var, FILTER_VALIDATE_REGEXP, array('options' => array('regexp' => '!' . self::$regexes[$type] . '!i'))) !== false;
return ($returnval);
}
$filter = false;
switch ($type) {
case 'email':
$var = substr($var, 0, 254);
$filter = FILTER_VALIDATE_EMAIL;
break;
case 'int':
$filter = FILTER_VALIDATE_INT;
break;
case 'boolean':
$filter = FILTER_VALIDATE_BOOLEAN;
break;
case 'ip':
$filter = FILTER_VALIDATE_IP;
break;
case 'url':
$filter = FILTER_VALIDATE_URL;
break;
}
return ($filter === false) ? false : filter_var($var, $filter) !== false ? true : false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment