Foros del Web » Programando para Internet » PHP »

PHP OO [aporte] sistema de validación de datos

Estas en el tema de [aporte] sistema de validación de datos en el foro de PHP en Foros del Web. Hola a todos, No sé dónde se ponen los aportes a la comunidad, así que... Abro este hilo :D. Hace no mucho desarrollé un sistema ...
  #1 (permalink)  
Antiguo 29/07/2011, 08:56
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
[aporte] sistema de validación de datos

Hola a todos,

No sé dónde se ponen los aportes a la comunidad, así que... Abro este hilo :D.

Hace no mucho desarrollé un sistema creado con PHP para validar datos, pero la falta de "ayuda" para realizar las pruebas me alejó del proyecto.

Sin embargo, hace unos días lo retomé, y hoy presento la versión 1 beta! :D.

La motivación es clara: mucha gente pregunta por cómo validar datos (esta comunidad es un buen ejemplo). Al ser una tarea repetitiva, he decidido crear esta clase, que permite validar datos con gran precisión y comodidad.

URL: http://www.magdkudama.com/validation

Se trata de una versión beta, no muy testeada... Os pido el favor de que la probéis, y que cualquier problema lo reportéis desde la web (donde también tenéis un tutorial, y un zip con la clase y ejemplos).

Mi objetivo es crear una clase perfectamente funcional y segura en un período de tiempo muy pequeño, con vuestra ayuda.

La web está en inglés y en castellano, pero la clase únicamente valida datos en lengua castellana!

Cualquier duda respecto a la forma de funcionar, comentar, por favor; ayudaré en lo posible :D.

Espero que sirva de algo.

PD: Ya que estamos, podéis pasar por mi blog! http://magdkudama.com/blog, que está muy vacíoooooo!
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #2 (permalink)  
Antiguo 29/07/2011, 11:02
 
Fecha de Ingreso: junio-2010
Ubicación: Venezuela, Zulia
Mensajes: 686
Antigüedad: 13 años, 9 meses
Puntos: 55
Respuesta: [aporte] sistema de validación de datos

bueno no la he revisado bien pero por los ejemplos que tiene hace falta algo que en el mismo formularioo al salir de X campo te de una mensaje de una vez si esta malo.

y no que al darle al boton enviar te borre todo si hay algo malo eso me saca de mis casillas
__________________
<?php echo "No te metas a lo hondo del Mar si no sabes nadar, primero aprende a nadar" ?>
...Error en linea: 1 o.O
  #3 (permalink)  
Antiguo 29/07/2011, 11:08
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Cita:
Iniciado por johhan16 Ver Mensaje
bueno no la he revisado bien pero por los ejemplos que tiene hace falta algo que en el mismo formularioo al salir de X campo te de una mensaje de una vez si esta malo.
Eso lo puedes lograr con el ejemplo4, dado que la validación se realiza mediante AJAX. La clase valida datos desde el servidor... Recuerda que validar datos en cliente no es seguro.

Cita:
Iniciado por johhan16 Ver Mensaje
y no que al darle al boton enviar te borre todo si hay algo malo eso me saca de mis casillas
Pero eso no tiene que ver con la clase en si... Eso es PHP puro. Lo puedes hacer en el value... De todas formas, eso puede ser una buena mejora, sin duda (aunque no quería llegar hasta allí, dado que (por ejemplo) con plantillas eso es una tarea muy sencilla ;D

Gracias por tus opiniones, muy amable
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #4 (permalink)  
Antiguo 29/07/2011, 11:27
Avatar de Uncontroled_Duck
Colaborador
 
Fecha de Ingreso: mayo-2011
Ubicación: Málaga [Spain]
Mensajes: 806
Antigüedad: 12 años, 11 meses
Puntos: 261
Respuesta: [aporte] sistema de validación de datos

Hola GrupoC,

Para el tema de los aportes creo que tienes que poner el código en el post...

Echale si quieres un vistazo a los que hay. (No los he mirado todos, pero los que he abierto tienen el code incluido)

Saludos,
__________________
Todos agradeceremos que pongas el código en su respectivo Highlight
  #5 (permalink)  
Antiguo 29/07/2011, 12:06
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Cita:
Iniciado por Uncontroled_Duck Ver Mensaje
Hola GrupoC,

Para el tema de los aportes creo que tienes que poner el código en el post...

Echale si quieres un vistazo a los que hay. (No los he mirado todos, pero los que he abierto tienen el code incluido)

Saludos,
De acuerdo, lo pondré en cuanto tenga un rato.

Gracias!
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #6 (permalink)  
Antiguo 30/07/2011, 01:36
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Hola a todos!

Código PHP:
<?php

/*   This script remains free until these lines are changed or removed
// +------------------------------------------------------------------------------------+
// | class.Validation.php    :    Allows you to validate any type of data sent by users   |
// |------------------------------------------------------------------------------------|
// |   This program is free software; you can redistribute it and/or                    |
// | modify it under the terms of the GNU General Public License                          |
// | as published by the Free Software Foundation of the License                         |
// |                                                                                    |
// |   This program is distributed in the hope that it will be useful,                  |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of                       |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the                       |
// | GNU General Public License for more details.                                        |
// |------------------------------------------------------------------------------------|  
// | Name of the script        :    class.Validate.php                                        |
// | Author                    :    Magd Kudama <[email protected]>                        |
// | Version                :    v1.0                                                    |
// | URL                    :    magdkudama.com/blog                                        |
// +------------------------------------------------------------------------------------+
*/

class Validation

{

    var 
$error_level;
    
    var 
$enviornment;
    
    var 
$count_elements=0;
    
    var 
$accnum="0";
    
    var 
$accsp="0";
    
    var 
$add_called=false;
        
    var 
$dec="<strong>ERROR:</strong> ";
    
    var 
$elements=array();
    
    var 
$errors_in_validation="";
    
    var 
$count;
    
    var 
$field;
    
    var 
$type;
    
    var 
$min;
    
    var 
$max;
    
    var 
$numdec;
    
    var 
$sql="0";
    
    var 
$sep;
    
    var 
$only;
    
    var 
$minchr;
    
    var 
$maxchr;
        
    var 
$tfh;
    
    var 
$like;
    
    var 
$minsize;
    
    var 
$maxsize;
    
    var 
$accformats;
    
    var 
$mindate;
    
    var 
$maxdate;
    
    var 
$element_separator="|";
    
    function 
is_assoc($arr)
    {
        return 
array_keys($arr)!==range(0,count($arr)-1);
    }
    
    private function 
showErrors($error)
    {
        die(
$error);
    }
    
    private function 
showValidation($text="")
    {
        
$sep=$this->element_separator;
        return empty(
$text) ? "1".$sep : ($this->error_level=="specific" $text.$sep "0".$sep);
    }
    
    public function 
__construct($error_level,$enviornment="development")
    {
        
$this->setErrorLevel($error_level);
        
$this->setEnviornment($enviornment);
    }
    
    private function 
setErrorLevel($error_level)
    {
        if(
in_array($error_level,array("specific","general")))
            
$this->error_level=$error_level;
        else
            
$this->showErrors($this->dec."You are not assigning a correct <strong>ERROR_LEVEL</strong>!");
    }
    
    private function 
setEnviornment($enviornment)
    {
        if(
in_array($enviornment,array("development","production")))
            
$this->enviornment=$enviornment;
        else
            
$this->showErrors($this->dec."You are not assigning a correct <strong>ENVIORNMENT</strong>!");
    }
    
    public function 
numberOfElements()
    {
        if(
$this->add_called)
            return 
$this->count;
        else
            
$this->showErrors($this->dec."You must call <em>addArray</em> before you call <em>numberOfElements</em>");
    }
    
    private function 
checkProperties($array)
    {
        
$required_properties=array("type","force","name","value");
        
        if(!
is_array($array))
            
$this->showErrors($this->dec."You must give an <em>array</em> of elements in order to check properties correctly");
        
        if(!
$this->is_assoc($array))
            
$this->showErrors($this->dec."You must give an <em>array</em> of properties!");
        
        
$array_keys=array_keys($array);
        
        if(
in_array("valid",$array_keys) && count($array_keys)!=4) {
            if(
count($array_keys)!=4)
                
$this->showErrors($this->dec."If you declare an array of valid values, you must only specify <em>name</em>, <em>force</em>, <em>valid</em> and the <em>value</em>");
            if(!
is_array($array["valid"]))
                
$this->showErrors($this->dec."The propertie <em>value</em> must be an array");
        }
        
        if(
in_array("valid",$array_keys))
            
array_shift($required_properties);
        else {
            if(
$array["type"]=="hour" && !isset($array["sep"]))
                
$this->showErrors($this->dec."You must give the propertie <em>sep</em> with an hour");
        }
        
        for(
$i=0;$i<count($required_properties);$i++)
            if(!
in_array($required_properties[$i],$array_keys))
                
$this->showErrors($this->dec."An element of the <em>array</em> has no ".$required_properties[$i]." declared");
        
        if(
count($array_keys)>8)
            
$this->showErrors($this->dec."Maximum of 8 properties per element exceeded");
        
        foreach(
$array as $key => $propertie)
        {
            switch(
$key)
            {
                case (
$key=="min" || $key=="max" || $key=="numdec"):
                    if(!
is_numeric($propertie))
                        
$this->showErrors($this->dec."The properties <em>min</em>, <em>max</em> and <em>numdec</em> must be numeric");
                    break;
                case 
"sep":
                    if(
strlen($propertie)!=1)
                        
$this->showErrors($this->dec."The properties <em>sep</em> must only have 1 character");
                    break;
                case (
$key=="sql" || $key=="tfh" || $key=="acc_num" || $key=="force"):
                    if(!
in_array($propertie,array("1","0")))
                        
$this->showErrors($this->dec."The properties <em>sql</em>, <em>acc_num</em>, <em>force</em> and <em>24h</em> must be in (0,1)");
                case (
$key=="minchr" || $key=="maxchr"):
                    if(
$propertie<0)
                        
$this->showErrors($this->dec."The properties <em>$key</em> must be higher than 0");
                    if(
$key=="minchr")
                        if((isset(
$array["maxchr"]) && $array["maxchr"]<$propertie))
                            
$this->showErrors($this->dec."The properties <em>minchr</em> must be smaller than <em>maxchr</em>");
                    else
                        if(isset(
$array["minchr"]) && $array["minchr"]>$propertie)
                            
$this->showErrors($this->dec."The properties <em>maxchr</em> must be greater than <em>minchr</em>");                        
                    break;
                case (
$key=="minsize" || $key=="maxsize"):
                    if(
$propertie<0)
                        
$this->showErrors($this->dec."The properties <em>$key</em> must be higher than 0");
                    if(
$key=="minsize")
                        if((isset(
$array["maxsize"]) && $array["maxsize"]<$propertie))
                            
$this->showErrors($this->dec."The propertie <em>minsize</em> must be smaller than <em>maxsize</em>");
                    else
                        if(isset(
$array["minsize"]) && $array["minsize"]>$propertie)
                            
$this->showErrors($this->dec."The propertie <em>maxsize</em> must be greater than <em>minsize</em>");                        
                    break;
                case (
$key=="mindate" || $key=="maxdate"):
                    if(
$key=="mindate")
                        if((isset(
$array["maxdate"]) && $array["maxdate"]<$propertie))
                            
$this->showErrors($this->dec."The propertie <em>mindate</em> must be smaller than <em>maxdate</em>");
                    else
                        if(isset(
$array["mindate"]) && $array["mindate"]>$propertie)
                            
$this->showErrors($this->dec."The propertie <em>maxdate</em> must be greater than <em>mindate</em>");                        
                    break;
                case 
"like":
                    if(
substr($propertie,0,1)!="%" && substr($propertie,-1)!="%")
                        
$this->showErrors($this->dec."The propertie <em>like</em> must have at least 1 character '%'");
                    break;
                case 
"only":
                    if(!
in_array(strtolower($propertie),array("ipv4","ipv6")))
                        
$this->showErrors($this->dec."The propertie <em>only</em> must be in (ipv4,ipv6)");
                    break;
                case 
"type":
                    
$types=array("integer","float","date","dni","email","url","string","file","ip","pass","hour");
                    if(!
in_array($propertie,$types))
                        
$this->showErrors($this->dec."The type <em>".$propertie."</em> is unknown!");                    
                    break;
                case 
"name":
                    if(!
ctype_alnum($propertie))
                        
$this->showErrors($this->dec."The propertie <em>name</em> must be alphanumerical");
                    break;
                case 
"value":
                    break;
                case 
"valid":
                    if(!
is_array($propertie))
                        
$this->showErrors($this->dec."The propertie <em>valid</em> must be an array");
                    if(
$this->is_assoc($propertie))
                        
$this->showErrors($this->dec."The propertie <em>valid</em> must not be an associative array");
                    break;
                case 
"accformats":    
                    if(!
is_array($array["accformats"]))
                        
$this->showErrors($this->dec."The propertie <em>accformats</em> must be an array");
                    break;
                default:
                    
$this->showErrors($this->dec."The propertie <em>$key</em> is unknown!");
            }
        }
    }
    
    public function 
addArray($array)
    {
        if(!
is_array($array))
            
$this->showErrors($this->dec."You must give an <em>array</em> as parameter");

        if(!
$this->add_called) {
            
$this->count=count($array);
            if(
$this->enviornment=="development") {
                for(
$i=0;$i<$this->count;$i++)
                    
$this->checkProperties($array[$i]);
            }
            
$this->elements=$array;
            
$this->add_called=true;
        }
        else
            
$this->showErrors($this->dec."The method <em>addArray</em> can only be called once");
    }
Esta es la primera parte del code (no me deja subir más de 10000 caracteres).
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #7 (permalink)  
Antiguo 30/07/2011, 01:37
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Código PHP:
private function validateINTEGER($value)
    {
        
$return="El campo $this->field ";
        
        if(!
ctype_digit(strval($value)))
            return 
$this->showValidation($return."ha de ser un n&uacute;mero entero");
        
        
$options=array("options"=>array());
        
        if(isset(
$this->min))
            
$options["options"]["min_range"]=$this->min;
        if(isset(
$this->max))
            
$options["options"]["max_range"]=$this->max;
        
        if(!
filter_var($valueFILTER_VALIDATE_INT,$options)) {
            if(isset(
$this->min) && isset($this->max))
                
$return.="ha de estar en el rango [$this->min - $this->max]";
            elseif(isset(
$this->min) && !isset($this->max))
                
$return.="ha de ser mayor que $this->min";
            elseif(!isset(
$this->min) && isset($this->max))
                
$return.="ha de ser menor que $this->max";
            return 
$this->showValidation($return);
        }
        return 
$this->showValidation();
    }
    
    private function 
validateFLOAT($value)
    {
        
$return="El campo $this->field ";
        
        if(!
is_numeric(strval($value)))
            return 
$this->showValidation($return."ha de ser un num&eacute;rico");

        if(
$this->numdec==0)
            return 
$this->validateINTEGER($value);
        
        if(!
filter_var($valueFILTER_VALIDATE_FLOAT)) 
            return 
$this->showValidation($return."no es un num&eacute;rico v&aacute;lido");

        if(
strpos($value,".")!==false) {
            
$qdecimals=explode(".",$value);
            
$qdecimals=strlen($qdecimals[1]);
            
            if(
$qdecimals!=$this->numdec)
                
$this->showValidation($return."ha de tener $this->numdec decimales");
            elseif(isset(
$this->min) || isset($this->max)) {
                if(isset(
$this->min) && !isset($this->max)) {
                    if(
$value<$this->min)
                        return 
$this->showValidation($return."ha de ser mayor que $this->min");
                }
                elseif(!isset(
$this->min) && isset($this->max)) {
                    if(
$value>$this->max)
                        return 
$this->showValidation($return."ha de ser menor que $this->max");
                }
                else {
                    if(
$value>$this->max || $value<$this->min) {
                        if(
$value>$this->max && $value>=$this->min)
                            return 
$this->showValidation($return."ha de ser menor que $this->max");
                        elseif(
$value<=$this->max && $value<$this->min)
                            return 
$this->showValidation($return."ha de ser mayor que $this->min");
                        else
                            return 
$this->showValidation($return."ha de estar en el rango [$this->min - $this->max]");
                    }
                }
            }
        }
        else
            return 
$this->showValidation($return."ha de tener $this->numdec decimales");
        return 
$this->showValidation();
    }
    
    private function 
extractDate($date)
    {
        
$date=explode($this->sep,$date);
        
$month=$date[1];
        if(
$this->sql==0) {
            
$year=$date[2];
            
$day=$date[0];
        }
        else {
            
$year=$date[0];
            
$day=$date[2];            
        }
        if(
$day<10$day="0".$day;
        if(
$month<10$day="0".$month;
        return 
$year.$month.$day;
    }
    private function 
validateDATE($value)
    {
        
$return="El campo $this->field ";
        
$date=explode($this->sep,$value);
        if(
count($date)!=|| strlen($value)!=10) {
            if(
$this->sql==0)
                
$format="dd".$this->sep."mm".$this->sep."yyyy";
            else
                
$format="yyyy".$this->sep."mm".$this->sep."dd";
            return 
$this->showValidation($return."no tiene el formato correcto ($format)");
        }
        
        
$month=$date[1];
        
        if(
$this->sql==0) {
            
$year=$date[2];
            
$day=$date[0];
        }
        else {
            
$year=$date[0];
            
$day=$date[2];            
        }
        
        if(!
checkdate((int)$month,(int)$day,(int)$year))
            return 
$this->showValidation($return."no es correcto (fecha inv&aacute;lida)");
            
        if(isset(
$this->mindate) && isset($this->maxdate)) {
            
$mindate=$this->extractDate($this->mindate);
            
$maxdate=$this->extractDate($this->maxdate);
            
$date=$this->extractDate($value);
            if(
$date>$maxdate || $date<$mindate)
                return 
$this->showValidation($return."ha de estar en el rango [$this->mindate , $this->maxdate]");
        }
        elseif(isset(
$this->mindate) && !isset($this->maxdate)) {
            
$mindate=$this->extractDate($this->mindate);
            
$date=$this->extractDate($value);
            if(
$date<$mindate)
                return 
$this->showValidation($return."ha de ser mayor que $this->mindate");
        }
        elseif(!isset(
$this->mindate) && isset($this->maxdate)) {
            
$maxdate=$this->extractDate($this->maxdate);
            
$date=$this->extractDate($value);
            if(
$date>$maxdate)
                return 
$this->showValidation($return."ha de ser menor que $this->maxdate");
        }
        
        return 
$this->showValidation();
    }

    private function 
DNI_Word($dni)
    {
        return 
substr("TRWAGMYFPDXBNJZSQVHLCKE",strtr($dni,"XYZ","012")%23,1);
    }
    
    private function 
validateDNI($value)
    {
        
$return="El campo $this->field ";
        if(
strlen($value)!=9)
            return 
$this->showValidation($return."debe contener 9 caracteres");
        
        
$last=strtoupper(substr($value,-1));
        
$first=strtoupper(substr($value,0,1));
        
$numbers=str_replace("X","0",strtoupper(substr($value,0,-1)));

        if(!
ctype_digit($first) && $first!="X")
            return 
$this->showValidation($return."es err&oacute;neo (revisar el primer caracter)");
        if(!
ctype_digit($numbers))
            return 
$this->showValidation($return."es incorrecto");
        if(
$this->DNI_Word($numbers)!=$last)
            return 
$this->showValidation("La letra del campo $this->field no es correcta");

        return 
$this->showValidation();
    }

    private function 
validateEMAIL($value)
    {
        
$return="El campo $this->field ";
        if(!
filter_var($valueFILTER_VALIDATE_EMAIL))
            return 
$this->showValidation($return."no tiene el formato correcto");
        return 
$this->showValidation();
    }
    
    private function 
validateURL($value)
    {
        
$return="El campo $this->field ";
        if(!
filter_var($valueFILTER_VALIDATE_URL))
            return 
$this->showValidation($return."no tiene el formato correcto");
        return 
$this->showValidation();
    }
    
    private function 
validateIP($value)
    {
        
$return="El campo $this->field no tiene el formato correcto ";
        
$option="";
        if(isset(
$this->only))
            
$option="FILTER_FLAG_".strtoupper($this->only);
        if(!
filter_var($valueFILTER_VALIDATE_IP,$option))
            if(isset(
$this->only))
                return 
$this->showValidation($return."(debe respetar el protocolo ".strtoupper($this->only).")");
            else 
                return 
$this->showValidation($return);
        return 
$this->showValidation();
    }

    private function 
validatePASS($value)
    {
        
$return="El campo $this->field ";
        if(isset(
$this->minchr) && strlen($value)<$this->minchr)
            return 
$this->showValidation($return."ha de tener como m&iacute;nimo $this->minchr caracteres");
        if(isset(
$this->maxchr) && strlen($value)>$this->maxchr)
            return 
$this->showValidation($return."ha de tener como m&aacute;ximo $this->maxchr caracteres");
        if (!
preg_match('`[a-z]`',$value))
            return 
$this->showValidation($return."ha de tener como m&iacute;nimo 1 letra min&uacute;scula");
        if (!
preg_match('`[A-Z]`',$value))
            return 
$this->showValidation($return."ha de tener como m&iacute;nimo 1 letra may&uacute;scula");
        if (!
preg_match('`[0-9]`',$value))
            return 
$this->showValidation($return."ha de tener como m&iacute;nimo 1 n&uacute;mero");
        return 
$this->showValidation();
    }

    private function 
validateHOUR($value)
    {
        
$return="El campo $this->field ";
        
$hour=explode($this->sep,$value);
        
        if(
strlen($value)!=5)
            return 
$this->showValidation($return."no es correcto");
        if(
count($hour)!=2) {
            
$format="HH".$this->sep."MM";
            return 
$this->showValidation($return."no tiene el formato correcto ($format)");
        }
        
        
$minute=$hour[1];
        
$hour=$hour[0];
        
        if(isset(
$this->tfh) && $this->tfh=="1") {
            if(
$hour<|| $hour>=24 || $minute<|| $minute>59)
                return 
$this->showValidation($return." no es una hora v&aacute;lida (ha de ser 24h)");
        }
        else {
            if(
$hour<|| $hour>=12 || $minute<|| $minute>59)
                return 
$this->showValidation($return." no es una hora v&aacute;lida (ha de ser 12h)");
        }
        return 
$this->showValidation();
    } 
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #8 (permalink)  
Antiguo 30/07/2011, 01:38
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Código PHP:
    private function validateSTRING($value)
    {
        
$return="El campo $this->field ";
        if(isset(
$this->minchr) && strlen($value)<$this->minchr)
            return 
$this->showValidation($return." debe tener como m&iacute;nimo $this->minchr caracteres");
        if(isset(
$this->maxchr) && strlen($value)>$this->maxchr)
            return 
$this->showValidation($return." debe tener como m&aacute;ximo $this->maxchr caracteres");
        if(
$this->accnum==&& preg_match('`[0-9]`',$value))
            return 
$this->showValidation($return." no puede contener n&uacute;meros");
        if(
$this->accnum==&& preg_match('`[0-9]`',$value))
            return 
$this->showValidation($return." no puede contener n&uacute;meros");
        if(
$this->accsp==&& strpos($value," ")!==false)
            return 
$this->showValidation($return." no puede contener espacios");

        if(isset(
$this->like)) {
            
$last=(substr($this->like,0,1)=="%") ? true false;
            
$first=(substr($this->like,-1)=="%") ? true false;

            
$str=str_replace("%","",$this->like);
            
            if(
$first && $last) {
                if(
strpos(strtolower($value),strtolower($str))===false)
                    return 
$this->showValidation($return." debe contener la cadena '$str'");
            } elseif(
$first) {
                if(
strtolower(substr($value,0,strlen($str)))!=strtolower($str))
                    return 
$this->showValidation($return." debe comenzar por '$str'");
            } elseif(
$last) {
                if(
strtolower(substr($value,-strlen($str)))!=strtolower($str))
                    return 
$this->showValidation($return." debe finalizar en '$str'");
            }
        }
        return 
$this->showValidation();
    }

    private function 
formatSize($size) {
        
$sizes = array(" Bytes"" KB"" MB"" GB"" TB"" PB"" EB"" ZB"" YB");
        return (
round($size/pow(1024,($i=floor(log($size1024)))),2).$sizes[$i]);
    }
    
    private function 
validateFILE($value,$row)
    {
        
$return="El campo $this->field ";
        
$size=$this->elements[$row]["value"]["size"];
        
$type=$this->elements[$row]["value"]["type"];

        
$minsize=(isset($this->minsize)) ? true false;
        
$maxsize=(isset($this->maxsize)) ? true false;

        if(
$minsize && $maxsize)
            if(
$size>$this->maxsize || $size<$this->minsize)
                return 
$this->showValidation($return." debe tener un tama&ntilde;o entre [".$this->formatSize($this->minsize)." , ".$this->formatSize($this->maxsize)."]");
        if(
$minsize && !$maxsize)
            if(
$size<$this->minsize)
                return 
$this->showValidation($return." debe tener un tama&ntilde;o mayor que ".$this->formatSize($this->minsize));
        if(
$maxsize && !$minsize)
            if(
$size>$this->maxsize)
                return 
$this->showValidation($return." debe tener un tama&ntilde;o menor que ".$this->formatSize($this->maxsize));
        
        if(isset(
$this->accformats)) {
            if(
array_search($type$this->accformats)===false) {
                
$string="[ ";
                for(
$i=0;$i<count($this->accformats);$i++) {
                    
$elements=explode("/",$this->accformats[$i]);
                    
$string.=$elements[1]." , ";
                }
                
$string=substr($string,0,-2)."]";
                return 
$this->showValidation($return." debe tener formato $string");
            }
        }
        
        return 
$this->showValidation();
    }
    
    private function 
unsetProperties()
    {
        
$this->accnum="0";
        
$this->accsp="0";
        
$this->sql="0";
        unset(
$this->field);
        unset(
$this->min);
        unset(
$this->max);
        unset(
$this->type);
        unset(
$this->min);
        unset(
$this->max);
        unset(
$this->numdec);
        unset(
$this->sep);
        unset(
$this->only);
        unset(
$this->minchr);
        unset(
$this->maxchr);
        unset(
$this->tfh);
        unset(
$this->like);
        unset(
$this->minsize);
        unset(
$this->maxsize);
        unset(
$this->accformats);
        unset(
$this->mindate);
        unset(
$this->maxdate);
    }
    public function 
validateElements()
    {
        for(
$i=0;$i<$this->count;$i++)
        {
            
$element=$this->elements[$i];
            
$this->field=$element["name"];
            
$this->valtype= isset($element["type"]) ? $element["type"] : "";
            
$force=$element["force"];
            
            if(isset(
$element["valid"]))
            {
                if(
array_search($element["value"],$element["valid"])===false)
                    
$this->errors_in_validation.=$this->showValidation("El campo $this->field no es correcto");
                else
                    
$this->errors_in_validation.=$this->showValidation();
                continue;
            }
            
            if(!
is_array($element["value"]) && $this->valtype!="file")
                
$value=$element["value"];
            else
                
$value=$element["value"]["name"];
            
            if(
$force==&& empty($value)) {
                
$this->errors_in_validation.=$this->showValidation();
                continue;
            }
            if(
$force==&& empty($value)) {
                
$this->errors_in_validation.=$this->showValidation("El campo $this->field es obligado");
                continue;
            }
            
            foreach(
$element as $attr => $propertie)
                
$this->$attr=$element[$attr];
            
            
$function=strtoupper($this->valtype);
            
$function="validate".$function;
            if(
$function=="validateFILE")
                
$this->errors_in_validation.=$this->$function($element["value"],$i);
            else
                
$this->errors_in_validation.=$this->$function($element["value"]);
            
            
$this->unsetProperties();
        }
        return 
substr($this->errors_in_validation,0,-1);
    }
}

?> 
Y esta es la última parte del code.

Espero que sirva de algo!
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #9 (permalink)  
Antiguo 01/08/2011, 09:22
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Dado que me lo han preguntado 6 de las 28 personas que han descargado el script, lo posteo aquí:

Pregunta: ¿Es posible validar cuentas bancarias?
Respuesta: Por el momento no, pero lo incluiré próximamente

Nuevamente os pido que la probéis :D.

Un saludo a todos.
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #10 (permalink)  
Antiguo 04/08/2011, 13:05
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Hola de nuevo a todos,

Gracias a todos por seguir probando el script, y ofreciéndome vuestras opiniones y recomendaciones.

Siguiendo los consejos de _ROOT y de Eltecom (usuarios del script), he decidido realizar unos cuantos cambios menores en el script:

- Por defecto, el tipo string acepta espacios y números.
- Dos errores en modo desarrollo, que mostraban mensajes de error con la función "accsp" y "accnum".

En cuanto tenga los cambios, posteo algo y cuelgo la nueva versión.

Nuevamente animaros a que probéis el script.

Muchas gracias a todos!
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #11 (permalink)  
Antiguo 06/08/2011, 14:02
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Bueno, ya está la nueva versión (v1.1) de la clase de validación de datos.

Para descargarla, http://magdkudama.com/validation

A ver si con vuestra ayuda la mejoro poco a poco.

Saludos!
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #12 (permalink)  
Antiguo 01/09/2011, 08:18
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Hola de nuevo,

He colgado la versión 2 (v 2.0) de la clase de validación de datos, con múltiples mejoras:

- Es un 12% más rápida (benchmarking realizado con las funciones de tiempo de PHP)
- Consume un 18% menos recursos (benchmarking realizado con memory_get_usage)
- Resueltos dos bugs de seguridad (en la validación del tipo hora)
- Añadido soporte multilenguaje mediante gettext

Aunque este hilo lleva tiempo, y no ha tenido demasiado éxito, os pido de nuevo vuestra colaboración, y que lo probéis. NO OS ARREPENTIRÉIS.

Para documentación y descargas: http://magdkudama.com/validation

Muchas gracias a todos.
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #13 (permalink)  
Antiguo 01/09/2011, 08:27
Avatar de JuJoGuAl  
Fecha de Ingreso: julio-2009
Ubicación: Venezuela
Mensajes: 754
Antigüedad: 14 años, 8 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Bueno a chequear haber como me funciona...
  #14 (permalink)  
Antiguo 01/09/2011, 08:30
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Gracias JuJoGuAl, cualquier problema me lo comentas (aunque la clase está documentada).

Un saludo!
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #15 (permalink)  
Antiguo 02/09/2011, 12:27
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Hola,

Me han preguntado (vía email) si es posible añadir el idioma francés (y otros).

¡La respuesta es sí! Al emplear gettext de PHP, esto es sencillisimo.

La forma más rápida es instalar POEDIT y crear el fichero .po (automáticamente se creará el .mo).

¡¡Vamos compañeros!! ¡Animaos a usarla!

Saludos (y gracias)!
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #16 (permalink)  
Antiguo 02/09/2011, 20:53
Avatar de mcun  
Fecha de Ingreso: octubre-2010
Ubicación: tras la pantalla
Mensajes: 466
Antigüedad: 13 años, 6 meses
Puntos: 55
Respuesta: [aporte] sistema de validación de datos

Bueno la probaremos ... y ya te daré mi opinión pero desde ya te agradezco que te ayas tomado el trabajo de real-izarlo y compartirlo

un saludo
  #17 (permalink)  
Antiguo 03/09/2011, 09:06
Avatar de JuJoGuAl  
Fecha de Ingreso: julio-2009
Ubicación: Venezuela
Mensajes: 754
Antigüedad: 14 años, 8 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Bueno yo la probe, ella no me die que error es, solo me dice que el formulario tiene error, pero no me dice cual. y nose si es ami pero se tardo bastante en validar, porque?????
  #18 (permalink)  
Antiguo 03/09/2011, 15:32
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Buenas,

Si estás utilizando el ejemplo de la web, cuando se valida correctamente, pone un mensaje de que está incorrecto, pero no lo muestra; es un ejemplo básico.

Prueba a dejar los campos sin rellenar, debería decirte que has de rellenarlos.

Saludos!
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #19 (permalink)  
Antiguo 04/09/2011, 04:38
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

En cuanto a lo de que va lento, me parece raro... Mira tu conexión. ¿Lo tienes colgado en alguna web?

La verdad es que tiene que ir muy rápido: en mis pruebas, ha sido más rápido que la versión 1 (que era más simple)... En validar 14 datos ha tardado 0.05 segundos...

Y el uso de memoria también ha disminuido...

Si sigues teniendo problemas, mándame un MP.

Saludos!
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #20 (permalink)  
Antiguo 10/09/2011, 18:16
Avatar de BaByRoDrI  
Fecha de Ingreso: julio-2009
Ubicación: Mexico
Mensajes: 60
Antigüedad: 14 años, 9 meses
Puntos: 1
Respuesta: [aporte] sistema de validación de datos

Yo quería preguntar a GrupoC como es que se logra disminuir el consumo de recursos y hacer más rapido el script :)

Espero me pudieras aclarar esas dudas! ;), por todo gracias!
  #21 (permalink)  
Antiguo 14/09/2011, 14:29
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Cita:
Iniciado por BaByRoDrI Ver Mensaje
Yo quería preguntar a GrupoC como es que se logra disminuir el consumo de recursos y hacer más rapido el script :)

Espero me pudieras aclarar esas dudas! ;), por todo gracias!
Buenas,

El consumo de recursos se refiere al espacio que ocupa en memoria el programa. Por ejemplo, al declarar variables estás consumiendo recursos (pocos, pero los consumes).

Crear un array multidimensional (por ejemplo) sí consume recursos apreciables...

La v2 del validador logra consumir menos recursos, evitando algunas declaraciones innecesarias en la clase anterior, y realizando un control de errores mucho más depurado, claro y conciso.

En cuanto al tiempo de ejecución, también ha disminuido, dado que existían dos funciones (principalmente checkProperies) que realizaban un control exhaustivo de los datos... Ahora he encontrado una forma de realizar el mismo control con menos código, recursos... y por tanto tiempo :D.

Puedes hacer las pruebas tú mismo empleando funciones de PHP.
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation
  #22 (permalink)  
Antiguo 14/09/2011, 14:34
 
Fecha de Ingreso: noviembre-2009
Mensajes: 226
Antigüedad: 14 años, 4 meses
Puntos: 19
Respuesta: [aporte] sistema de validación de datos

Aprovecho para pediros vuestras opiniones, dado que voy a desarrollar una nueva versión, que soluciona pequeños errores (reportados desde la web) y otras validaciones que pueden faltar... (cuenta de banco, por ejemplo).

Os pido consejos de cómo mejorar la aplicación, que parece que poca gente la ha probado :S

Muchas gracias!
__________________
Mi blog: magdkudama.com

Mi clase de validación de datos: magdkudama.com/validation

Etiquetas: sistema, validar
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 2 personas




La zona horaria es GMT -6. Ahora son las 05:15.