Visualizzazione dei risultati da 1 a 3 su 3
  1. #1

    assegnare un nome ad ogni valore di un array

    Salve. Ho letto l'articolo che parla di come gestire la validazione di un form tramite la programmazione ad oggetti (http://freephp.html.it/articoli/view...olo.asp?id=139 )
    Tutto bene, ho capito come funziona. Ora vorrei modificarla. In pratica quando viene aggiunto un errore esso viene aggiunto ad un array e poi tutti gli errori vengono mostrati insieme e poi viene mostrato il form in questo modo:

    Errore 1
    errore 2
    errore 3

    form

    Io voglio fare in modo di mostrare ogni errore sopra al proprio campo.

    Di conseguenza invece di far aggiungere il valore all'array senza specificare il nome ($errors[] = $errore vorrei fare in modo di specificare un nome per ogni valore ($errors['nome_campo'] = errore). Il problema è che come ho modificato lo script non funziona! All'array gli errori vengono aggiunti sempre sequenzialmente utilizzando i numeri progressivamente senza assegnare il nome.

    Sotto vi posto i due files in questione:

    Codice PHP:
    // Classe che rappresenta un campo singolo di un form
    class FrmField extends AbstrErrHandler
         
    {
            
    // Le regole da applicare
            
    var $rules ;
        
            
    // Il valore contenuto dal campo
            
    var $val ;
        
            
    // Il valore da attribuire di default
            
    var $defVal ;
        
            
    // L'etichetta del campo
            
    var $label ;
        
            
    // Il campo è obbligatorio?
            
    var $req ;

            
    // Costruttore
            
    function FrmField($val$label$required$rules = array(), $default '' )
                    {   
                       
    parent::AbstrErrHandler() ;
                       
    $this->rules = &$rules  ;   
                       
    $this->label $label ;
                       
    $this->req $required ;
              
                       
    // Se la variabile non esiste viene settata ad un valore di default
                       
    if (!isset($val))
                         {
                            
    $val $default ;
                         }
                       
    $this->val = &$val ;
                       
    $this->defVal $default ;
                    }       
        
            function 
    validate()
                    {
                       
    // Se il campo è vuoto
                       
    if (empty($this->val))
                         {
                            
    // Se è obbligatorio
                            
    if ($this->req)
                              {
                                 
    // Se è obbligatorio settiamo un errore
                                 
    $this->errors["$this->label"] = sprintf(IS_REQUIRED$this->label) ;
                              }
                            
    // Se vuoto e non obbligatorio inutile fare altri controlli e usciamo
                            
    return ;   
                         }
    //END if empty
            
                    // Altrimenti procediamo ai controlli successivi
                    
    while (list(, $rule) = each($this->rules))
                         {
                            
    $rule->check($this->val$this->label) ;
                            if (!
    $rule->isValid())
                              {    
                                 
    $this->errors["$this->label"] = $rule->getError() ;
                                 
    // In caso di errori ripristina il valore di default al 
                                 // posto di quello non corretto
                                 
    $this->val $this->defVal ;
                                 return ;
                              }
                          }
    //end while
                    
    }//end function validate
         
    }//end class

    // Classe che rappresenta un campo multiplo (es. select multipla) di un form
    class FrmFieldSet extends AbstrErrHandler
         
    {
            
    // L'array di valori contenuti nel fieldset
            
    var $val ;
            
            
    // Le regole da applicare all'intero fieldset
            
    var $fieldSetR ;
        
            
    // Le regole da applicare ai singoli valori contenuti
            
    var $fieldR ;
        
            
    // L'etichetta del fieldset
            
    var $label ;
        
            
    // Il valore da attribuire di default
            
    var $defVal ;
        
            
    // Il campo è obbligatorio?
            
    var $req ;
        
            function 
    FrmFieldSet($sentVals$label$required$fieldSetRules = array(), $fieldRules = array(), $default = array() )
                    {
                       
    parent::AbstrErrHandler() ;
                       
    // Se la variabile non esiste viene settata ad un valore di default
                       
    if (!isset($sentVals))
                         {
                            
    $sentVals $default ;        
                         }
                       
    $this->val = &$sentVals ;
                       
    $this->req $required ;
                       
    $this->defVal $default ;
                       
    $this->label $label ;
                       
    $this->fieldSetR = &$fieldSetRules ;
                       
    $this->fieldR = &$fieldRules ;
                    }
            
            
    // Determina se un valore è presente nel fieldset
            
    function selected($what)
                    {
                       return 
    in_array($what$this->val) ;
                    }
        
            
    // Esegue i controlli sul fieldset
            
    function validate()
                    {
                       
    // Se il campo è vuoto
                       
    if (empty($this->val))
                         {
                            
    // Se è obbligatorio settiamo un errore
                            
    if ($this->req)
                              {
                                 
    $this->errors["$this->label"] = sprintf(IS_REQUIRED$this->label) ;
                              }
                       
                            
    // Se vuoto e non obbligatorio inutile fare altri controlli e usciamo
                            
    return ;   
                         }
    //END if empty
            
                       // Altrimeti ciclo di controlli sul fieldset nel suo complesso
                       
    while (list(, $rule) = each$this->fieldSetR) )
                            {
                               
    $rule->check($this->val$this->label) ;
                               if (!
    $rule->isValid())
                                 {    
                                    
    $this->errors["$this->label"] = $rule->getError() ;
                                    
                                    
    // In caso di errori ripristina il valore di default al 
                                    // posto di quello non corretto
                                    
    $this->val $this->defVal ;
                                    return ;
                                 }
                            }
    //end while  
                    
                       // ciclo di controlli su ogni campo nel fieldset
                       
    while (list(, $rule) = each($this->fieldR))
                            {
                               while (list(, 
    $field) = each($this->val))
                                    {
                                       
    $rule->check($field$this->label) ;
                                       if (!
    $rule->isValid())
                                         {    
                                            
    $this->errors["$this->label"] = $rule->getError() ;
                                            
    // Ripristina il valore di default al 
                                            // posto di quello non corretto
                                            
    $this->val $this->defVal ;
                                            return ;
                                         }
    //END if
                                    
    //END while2
                            
    //END while1 
                    
    }//end function "validate"
         
    }//END class

    class CapField extends FrmField
         
    {
            function 
    CapField($val$label$required$default='')
                    {
                       
    $rules = array() ;
                       
    $rules[] = new PatternRule("/^\d{5}$/") ;
                       
    parent::FrmField($val$label$required$rules$default) ;
                    }
         }
    //end class

    class MailField extends FrmField
        
    {
           function 
    MailField($val$label$required$default='')
                   {     
                      
    $rules = array() ;   
                      
    $rules[] = new PatternRule("/^[a-zA-Z]{1}\w{1,10}[-|.|_]{0,1}\w{0,10}@\w{3,10}\.\w{0,10}-{0,1}\w{0,10}\.{0,1}\w{2,6}$/i") ;
                      
    parent::FrmField($val$label$required$rules$default) ;    
                   } 
        }
    //end class

    class PhoneField extends FrmField
         
    {
            function 
    PhoneField($val$label$required$default='')
                    {
                       
    $rules = array() ;
                       
    $rules[] = new PatternRule("/^\+{0,1}\d{0,4}[-|\\\| |\/]{0,1}\d{3,5}[-|\\\|\/]{0,1}\d{5,10}$/U") ;
                       
    parent::FrmField($val$label$required$rules$default) ;    
                    }
         }
    //end class 

  2. #2
    E questo è l'altro file
    [PHP]
    Codice PHP:
    /*
    Classe astratta, definisce il modello da cui deriveranno tutte le altre regole
    */
    class AbstractRule extends AbstrErrHandler
         
    {
            
    // Contiene i messaggi di errore
            
    var $errors  = array() ;

            
    // costruttore
            
    function AbstractRule()
                    {
                       
    parent::AbstrErrHandler() ;
                    }

            
    // Effettua il parsing alla caccia di errori
            // riceve come argomenti il valore e l'etichetta del campo
            
    function check($val$label)
                    {
                    }
         }
    //end class

    // Verifica la lunghezza di una stringa
    class StrRangeRule extends AbstractRule
         
    {
            
    // la lunghezza massima e quella minima
            
    var $min ;
            var 
    $max ;

            function 
    StrRangeRule($min$max)
                    {
                       
    parent::AbstractRule() ;
                       
    $this->min $min ;
                       
    $this->max $max ;
                    }

            
    // Verifica che il campo contenga una stringa compresa entro un certo range di caratteri
            
    function check($val$label)
                    {
                       
    $val trim($val) ;
                       
    $len =  strlen($val) ;
                       if (
    $this->min == $this->max)
                         {
                            if ((bool)
    $this->min)
                              {
                                 
    // Il valore non è 0
                                 // il controllo non è disabilitato
                                 
    $this->checkFixedLen($len$label) ;   
                              }
                            
    // Il valore è 0 
                            // il controllo disabilitato
                            
    return ;
                         }
                       elseif (
    $this->min == 0)
                         {   
                            
    // E' necessario verificare solo max
                            
    $this->checkMax($len$label) ;
                         }
                       elseif( 
    $this->max == )
                         {   
                            
    // E' necessario verificare solo min
                            
    $this->checkMin($len$label) ;
                         }
                       else
                         {   
                            
    // E' necessario verificare entrambi
                            
    $this->checkBoth($len$label) ;
                         }
                    }
    //end check

            
    function checkMin($len$label)
                    {
                       if (
    $len $this->min)
                         {
                            
    $this->errors["$label"] = sprintf(STR_TOO_SHORT$label$this->min) ;
                         }
                    }
    //end checkMin

            
    function checkMax($len$label)
                    {
                       if (
    $len $this->max)
                         {
                            
    $this->errors["$label"] = sprintf(STR_TOO_LONG$label$this->max)  ;
                         }
                    }
    //end checkMax

            
    function checkBoth($len$label)
                    {
                       if (
    $len $this->min || $len $this->max)
                         {
                            
    $this->errors["$label"] = sprintf(STR_BAD_RANGE$label$this->min$this->max) ;
                         }
                    }
    //end checkBoth
        
            
    function checkFixedLen($len$label)
                    {
                       if ( 
    $len != $this->min )
                         { 
                            
    $this->errors["$label"] = sprintf(STR_BAD_LEN$label$this->min) ;
                         }
                    }
    //end checkFixed
         
    }//end class

    // Verifica la corrispondenza a un pattern
    class PatternRule extends AbstractRule
         
    {
            var 
    $regex ;
            function 
    PatternRule($regex)
                    {
                       
    parent::AbstractRule() ;
                       
    $this->regex $regex ;
                    }

            function 
    check($val$label)
                    {
                       
    $val trim($val) ;
                       if (!
    preg_match($this->regex$val))
                         {
                            
    $this->errors["$label"] = sprintf(BAD_PATTERN$label) ;
                         }
                    }
         }
    //end class

    // Verifica se un campo è di tipo numerico
    class IsNumericRule extends AbstractRule
         
    {
            
    // Costruttore
            
    function isNumericRule()
                    {
                       
    // Costruttore della classe genitore astratta         
                       
    parent::AbstractRule();
                    }

            function 
    check($val$label)
                    {
                       if (!
    is_numeric($val))
                         {
                            
    $this->errors["$label"]  = sprintf(NOT_NUM$label) ;
                         }
                    }
         }
    //end class

    // Verifica il valore umerico di un campo è compreso in un dato range
    class NumRangeRule extends IsNumericRule
         
    {
            
    // il valore massimo e quello minimo
            
    var $min ;
            var 
    $max ;

            function 
    NumRangeRule($min$max)
                    {
                       
    parent::IsNumericRule();
                       
    $this->min $min ;
                       
    $this->max $max ;
                    }

            function 
    check($val$label)
                    {
                       
    parent::check($val$label);
                       if (
    $this->isValid() && ( $val $this->min || $val $this->max ))
                         {
                            
    $this->errors["$label"] = sprintf(NUM_BAD_RANGE$label$this->min$this->max) ;
                         }
                    }
         }
    //end class

    // Verifica se il contenuto di un campo fa parte di una lista predefinita di valori
    class InListRule extends AbstractRule
         
    {
            var 
    $list ;
            function 
    InListRule($arrValues)
                    {
                       
    parent::AbstractRule() ;
                       
    $this->list $arrValues ;
                    }
        
            function 
    check($val$label$strict false)
                    {
                       if (!
    in_array($val$this->list$strict))
                         {
                            
    $this->errors["$label"] =  sprintf(NOT_IN_LIST$label) ;
                         }
                    }
    //end function check
         
    }//end class

    // Verifica se un stringa ne contiene un'altra
    class ContainsRule extends AbstractRule
         
    {
            function 
    ContainsRule($startStr)
                    {
                       
    parent::AbstractRule() ;
                       
    $this->str  strtolower($startStr) ;
                    }
        
            function 
    check($val$label)
                    {
                       
    $pos strpos(strtolower($val), strtolower($this->str)) ;
                       if (
    $pos === false)
                         {
                            
    $this->errors["$label"] = sprintf(CONTAIN_ERR$label$this->str) ;            
                         }
                    }    
         }
    //END class

    // Verifica se un stringa inizia con un'altra
    class StartsWithRule extends AbstractRule
         
    {
            
    // La stringa da cercare
            
    var $str ;

            function 
    StartsWithRule($startStr)
                    {
                        
    parent::AbstractRule() ;
                        
    $this->str  strtolower($startStr) ;
                    }
        
            function 
    check($val$label)
                    {
                       
    parent::check($val$label) ;
                       
    $val strtolowertrim($val) ) ;
        
                       
    // confronto esatto sul tipo
                       
    if (!strpos($val$this->str) === 0)
                         {
                            
    $this->errors["$label"] = sprintf(STARTWITH_ERR$label$this->str) ;
                         }
                    }
         }
    //end class

    // Verifica se un stringa termina con un'altra
    class EndsWithRule extends ContainsRule
         
    {
            function 
    EndsWithRule($startStr)
                    {
                       
    parent::ContainsRule($startStr) ;
                    }
        
            function 
    check($val$label)
                    {
                       
    parent::check($val$label) ;
                       
    $endPos substr($val, -( strlen($this->str ) ) ) == $this->str  ;
                       if (
    $this->isValid() && !$endPos )
                         {
                            
    $this->errors["$label"] = sprintf(ENDWITH_ERR$label$this->str) ;
                         }
                    }
         }
    //END class

    // Verifica che il contenuto di un fieldset multiplo
    // contenga un dato numero di elementi o sia compreso in un certo range
    class NumElementsRule extends AbstractRule
         
    {
            
    // I limiti ammessi
            
    var $min ;
            var 
    $max ;

            function 
    NumElementsRule($min$max)
                    {
                       
    parent::AbstractRule() ;
                       
    $this->min $min ;
                       
    $this->max $max ;
                    }
        
            function 
    check($val$label)
                    {
                       
    $count is_array($val) ? count($val) : ;
                       if (
    $this->min == $this->max)
                         {
                            if ((bool)
    $this->min)
                              {
                                 
    // Il valore non è 0
                                 // il controllo non è disabilitato
                                 
    $this->checkFixedNum($count$label) ;   
                              }
                            
    // Il valore è 0 
                            // il controllo disabilitato
                            
    return ;
                         }
                       elseif (
    $this->min == 0)
                         {   
                            
    // E' necessario verificare solo max
                            
    $this->checkMax($count$label) ;
                         }
                       elseif (
    $this->max == 0)
                         {   
                            
    // E' necessario verificare solo min
                            
    $this->checkMin($count$label) ;
                         }
                       else
                         {   
                            
    // E' necessario verificare entrambi
                            
    $this->checkBoth($count$label) ;
                         }
                    }
    //end check
        
            
    function checkMin($count$label)
                    {
                       if (
    $count $this->min)
                         {
                            
    $this->errors["$label"] = sprintf(ARR_TOO_SHORT$label$this->min) ;
                         }
                    }
    //end checkmin
        
            
    function checkMax($count$label)
                    {
                       if (
    $count $this->max)
                         {
                            
    $this->errors["$label"] = sprintf(ARR_TOO_LONG$label$this->max) ;
                         }
                    }
    //end checkmax
        
            
    function checkBoth($count$label)
                    {
                       if (
    $count $this->min || $count $this->max)
                         {
                            
    $this->errors["$label"] = sprintf(ARR_BAD_RANGE$label$this->min$this->max) ;
                         }
                    }
    //end checkboth
        
            
    function checkFixedNum($count$label)
                    {
                       if (
    $count != $this->min)
                         {
                            
    $this->errors["$label"] = sprintf(ARR_BAD_LEN$label$this->min) ;
                         }
                    }
    //end checkFixedNum
         
    }//end class

    // Verifica che il contenuto di un fieldset multiplo contenga uno o più elementi predefiniti
    class HasElementsRule extends AbstractRule
         
    {
            
    // Gli elementi da cercare
            
    var $elements ;
        
            function 
    HasElementsRule($arrElms)
                    {
                       
    parent::AbstractRule() ;
                       
    $this->elements $arrElms ;
                    }
        
            function 
    check$val$label$allRequired false )
                    {
                       
    $result array_intersect($this->elements$val) ; 
                       
    $error sprintf(LACK_OF_ELEMENTS$label) ; 
                       if (
    $allRequired)
                         {
                            if (
    count($result) < count($this->elements))
                              {
                                 
    $this->errors["$label"] = $error 
                              }
                         }
                       elseif (empty(
    $result))
                         {
                            
    $this->errors["$label"] = $error ;
                         }
                    }
    //END function
         
    }//END class 
    L'array in questiona è $this->errors[]

  3. #3
    Ho fatto progressi. Ho capito perchè non assegna i valori. Perchè le variabili di errore vengono passate a questa funzione:

    Codice PHP:
    function getError()
                    {
                       return 
    array_shift($this->errors) ;
                
                    } 
    Modificandola in questo modo riesco a vedere tutto il contenuto della variabile:

    Codice PHP:
    function getError()
                    {
                       while (list(
    $var,$value) = each ($this->errors))
                             {
                                
    $this->errors[$var] = $value;
                             }
                        return 
    $this->errors;
                    } 
    Il problema è che risulta un array del genere

    array ( 0 => array ( 'Nome' => '"Nome" è un campo obbligatorio', ), 1 => array ( 'Cognome' => '"Cognome" è un campo obbligatorio', ), 2 => array ( 'Userid' => '"Userid" è un campo obbligatorio', ), 3 => array ( 'Password 1' => '"Password 1" è un campo obbligatorio', ), 4 => array ( 'Password 2' => '"Password 2" è un campo obbligatorio', ))

    Come faccio ad eliminare gli array numerici e ad assegnare direttamente il nome della variabile?

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.