Ver Mensaje Individual
  #1 (permalink)  
Antiguo 24/05/2012, 07:31
kindah
 
Fecha de Ingreso: agosto-2009
Ubicación: Buenos Aires
Mensajes: 13
Antigüedad: 14 años, 8 meses
Puntos: 0
Class de validacion

Bueno, primero que nada, gracias por tomarte la molestia de leer el mensaje, y segundo, disculpa si escribo bestialidades, soy muy novato en todo este asunto de php...

Recientemente me puse a trabajar en una pagina web, y actualmente estoy haciendo el formulario de contacto.. normalucho, nada del otro mundo... pero quiero hacer un class de validacion para usarlo a futuro en otros forms, como puede ser login, o ingresar datos a la db, es por eso mismo que quiero hacerlo de un modo que me funcione y obviamente, me sea entendible con mi poco nivel de programacion.
La idea seria la siguiente:

En el php donde iria el form:
Código PHP:
Ver original
  1. <?php  
  2.  
  3.     if (isset($_POST['Submit'])) {  
  4.  
  5.         $functions->validarNombre($_POST['name'],'15','50');
  6.         if (!$errors) {  
  7.             //envia el email  
  8.             echo "gracias por el email pepito!!<br/><br/>";  
  9.         } else {  
  10.             echo '<div class="error_box">' . $errors . '<br/></div>';  
  11.         }  
  12.     }  
  13. ?>

La class de validacion:
Código PHP:
Ver original
  1. <?
  2. if (basename($_SERVER["REQUEST_URI"]) === basename(__FILE__))
  3. {
  4.     exit();
  5. }
  6.  
  7. class functions extends nwMySQL
  8. {  
  9.     var $username;
  10.     var $password;
  11.    
  12.    
  13.     function validarNombre($name, $min_length, $max_length)
  14.     {
  15.         if ($name != "")
  16.         {
  17.             $name = filter_var($name, FILTER_SANITIZE_STRING);  
  18.             if ($name == "")
  19.             {  
  20.                 $errors .= 'Please enter a valid name.<br/><br/>';  
  21.             }
  22.             elseif (strlen($name) < $min_length)
  23.             {
  24.                 $errors .= 'Please enter a valid name.<br/><br/>';  
  25.             }
  26.             elseif (strlen($name) > $max_length)
  27.             {
  28.             $errors .= 'Please enter a valid name.<br/><br/>';  
  29.             }
  30.         }
  31.         else
  32.         {  
  33.             $errors .= 'Please enter your name.<br/>';  
  34.         }  
  35.     }
  36. }
  37.  
  38. ?>

La llamo en el index.php de la web de la siguiente manera:
Código PHP:
Ver original
  1. <?
  2. header("Cache-control: private");
  3. ob_start("ob_gzhandler");
  4.  
  5. require ('_modulos/configuracion.php');
  6. require ('_modulos/mysql.class.php');
  7. require ('_modulos/functions.class.php');
  8. require ('_modulos/lenguajes.class.php');
  9. require ('_modulos/paginacion.class.php');
  10. $Contenido = $_REQUEST['go'];
  11. if($Contenido == '')
  12.     {
  13.     $Contenido = 'inicio';
  14.     }
  15. $nwMy = new nwMySQL;
  16. $nwMy->Connect();
  17. $functions = new functions();
  18.  
  19. ?>

La pregunta principal seria, como hago para imprimir/chequear el $errors en el php del formulario?

Si se preguntan porque esta todo en spanglish es porque me resulta facil acordarme algunas funciones en español y otras en ingles...

Por si a alguien le es de ayuda tmb, el codigo original del formulario de php lo saque de aca: http://net.tutsplus.com/tutorials/php/sanitize-and-validate-data-with-php-filters/


Bueno, lo solucione por mi cuenta, por si a alguien le ayuda, dejo el codigo actual, tambien si ven algo incorrecto y me lo corrigen, se los agradeceria.

Código PHP:
Ver original
  1. <?
  2. if (basename($_SERVER["REQUEST_URI"]) === basename(__FILE__))
  3. {
  4.     exit();
  5. }
  6. require ("lenguajes.class.php");
  7.  
  8. class functions extends nwMySQL
  9. {  
  10.     var $username;
  11.     var $password;
  12.     var $errors;
  13.     //Validar variable para nombre/login, con minimo y maximo de caracteres
  14.     function validarTexto($valor_input, $min_length, $max_length,$nombreinput)
  15.     {
  16.         if ($valor_input != "")
  17.         {
  18.             $valor_input = filter_var($valor_input, FILTER_SANITIZE_STRING);
  19.             $input_length = strlen($valor_input);  
  20.             if ($valor_input == "")
  21.             {  
  22.                 $this->errors[] = sprintf(formvalidator_fieldinvalid,$nombreinput);
  23.                 return false;
  24.             }
  25.             if ($input_length < $min_length)
  26.             {
  27.                 $this->errors[] = sprintf(formvalidator_fieldminlenght,$nombreinput,$min_length);
  28.                 return false;
  29.             }
  30.             if ($input_length > $max_length)
  31.             {
  32.                 $this->errors[] = sprintf(formvalidator_fieldmaxlenght,$nombreinput,$max_length);
  33.                 return false;
  34.             }
  35.         }
  36.         else
  37.         {
  38.             $this->errors[] = sprintf(formvalidator_fieldrequired,$nombreinput);
  39.             return false;
  40.         }
  41.         unset($valor_input);   
  42.     }
  43.     //Validar direcciones de E-Mail
  44.     function validareMail($valor_input,$nombreinput)
  45.     {
  46.         if ($valor_input != "")
  47.         {
  48.             $valor_input = ereg("^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$", $valor_input);
  49.             if ($valor_input == "")
  50.             {  
  51.                 $this->errors[] = sprintf(formvalidator_fieldinvalid,$nombreinput);
  52.                 return false;
  53.             }
  54.         }
  55.         else
  56.         {
  57.             $this->errors[] = sprintf(formvalidator_fieldrequired,$nombreinput);
  58.             return false;
  59.         }  
  60.         unset($valor_input);  
  61.     }
  62.     function validarNumero($valor_input,$min_length,$max_length,$nombreinput)
  63.     {
  64.         if ($valor_input != "")
  65.         {
  66.             $input_length = strlen($valor_input);  
  67.             if (!preg_match("/^[0-9]+$/", $valor_input))
  68.             {  
  69.                 $this->errors[] = sprintf(formvalidator_fieldnumeric,$nombreinput);
  70.                 return false;
  71.             }
  72.             if ($input_length < $min_length)
  73.             {
  74.                 $this->errors[] = sprintf(formvalidator_fieldminlenght,$nombreinput,$min_length);
  75.                 return false;
  76.             }
  77.             if ($input_length > $max_length)
  78.             {
  79.                 $this->errors[] = sprintf(formvalidator_fieldmaxlenght,$nombreinput,$max_length);
  80.                 return false;
  81.             }
  82.         }
  83.         else
  84.         {
  85.             $this->errors[] = sprintf(formvalidator_fieldrequired,$nombreinput);
  86.             return false;
  87.         }
  88.         unset($valor_input);           
  89.     }
  90.     // Chequea si se encontraron errores.
  91.     function validarbuscarErrors()
  92.     {
  93.         if (count($this->errors) > 0)
  94.         {
  95.             return true;
  96.         }
  97.         else
  98.         {
  99.             return false;
  100.         }
  101.     }
  102.  
  103.     // Devuelve una lista de errores, separados por un elemento customizado.
  104.     function validarlistarErrors($delim = '')
  105.     {
  106.         return implode($delim,$this->errors);
  107.     }
  108. }
  109.  
  110. ?>

Para mostrar los errores:
Código PHP:
Ver original
  1. if (isset($_POST['Enviar'])) {  
  2.  
  3.         $functions->validarTexto($_POST['name'],'5','30',contact_contactform_nameandlastname);
  4.         $functions->validarNumero($_POST['phone'],'8','15',contact_contactform_telephone);
  5.         $functions->validarNumero($_POST['cellphone'],'10','17',contact_contactform_cellphone);
  6.         $functions->validarTexto($_POST['estate'],'5','30',contact_contactform_estate);
  7.         $functions->validarTexto($_POST['city'],'5','30',contact_contactform_city);
  8.         $functions->validareMail($_POST['email'],contact_contactform_email);
  9.         $functions->validarTexto($_POST['message'],'10','1000',contact_contactform_yourmessage);
  10.         if (!$functions->validarbuscarErrors())
  11.         {  
  12.             //envia el email  
  13.             echo '<div class="ok_box">gracias por el email pepito!!<br/></div>';  
  14.         }
  15.         else
  16.         {  
  17.             echo '<div class="error_box">'.$functions->validarlistarErrors('<br />'). '</div>';  
  18.         }  
  19.     }

Última edición por kindah; 24/05/2012 a las 09:50 Razón: me olvide la pregunta principal