bonjour!
je vous propose ce matin coe ptit dej (lol) cette classe à intégrer au systeme MVC proposé par grafikart et
qui simplifiera drastiquement la procédure de validation des données soumises . L'avantage ici resides dans le fait que pour un même champs on peut definir plusieur regles de validation (ex: $validates=array('message'=>array('notempty','text','maxlen'=>400,'minlen'=>100)) ). bien évidement cela implique quelques modifications au niveau de la methode "validates" de la classe model. voici la version modifiée.

/**
            *Permet de valider les données reçue des formulaires
            *
            **/
    public function validates($data){
        $errors = array();
        if(!class_exists('ValidatorHelper',true)) Include(HELPERPATH.DS.'ValidatorHelper.php'); //adapter le chemin à votre site
        $validator = new ValidatorHelper($data);
        foreach($this->validate as $field=>$rules)
        {
            if(!is_array($rules)) $rules = explode(',',trim($rules,','));
            foreach($rules as $each=>$rule)
            {
                if(!$validator->isValid($each,$field,$rule)) $errors$field] = $validator->message;
            }
        }//endforeach
        //IrivenCMS::debug($errors); 
        $this->errors = $errors;
        if(isset($this->Form))  $this->Form->errors = $errors;
        if(empty($errors)) return true;
        return false;
        }

et la classe de validation

<?php /**
 * IrivenCMS Pro : Rapid Development Framework (http://www.iriven.com)
 * Copyright 2008-2013, Iriven France Software, Inc. 
 *
 * Licensed under The MIT License
 * Redistributions of files must retain the above copyright notice.
 *
 * @copyright Copyright 2008-2013, Iriven France Software, Inc.
 * @link http://www.iriven.com IrivenCMS Project
 * @package IrivenCMS.Utility
 * @since IrivenCMS Pro v 1.0.4
 * @license MIT License (http://www.opensource.org/licenses/mit-license.php)
 */
class ValidatorHelper{
    public $message;
    private $origin;
    private $field;
    private $min;
    private $max;
    private $to;
    private $rel;
    private $format;
    private $reserved= array();//si methode => ne peut faire l'objet de type de validation. si attribut de cette classe => ne peut etre reinitialisé à null
    private $errorMsg = array(
                            'text'=>'contient des données pouvant compromettre la sécurité du site.',
                            'siret'=>'n\'est pas un numéro de siret valide!',
                            'ape'=>'n\'est pas un code APE valide!',
                            'string'=>'n\'est pas de type chaine de caractères!',
                            'filename'=>'n\'est pas un nom de fichier valide!',
                            'dirname'=>'n\'est pas un nom de repertoire valide!',
                            'absurl'=>'doit être une url absolue (Ex: http://www.example.com)',
                            'tracking'=>'n\'est pas un numéro de suivi valide!',
                            'color'=>'n\'est pas un code de couleur valide!',
                            'percent'=>'doit être un pourcentage!',
                            'postcode'=>'n\'est pas un code postale valide!',
                            'phone'=>'n\'est pas un numéro de téléphone valide!',
                            'ean13'=>'n\'est pas un numéro de code barre valide!',
                            'birthdate'=>'n\'est pas une date anniversaire valide!',
                            'adresse'=>'n\'est pas une adresse valide!',
                            'cityname'=>'n\'est pas un nom de ville valide!',
                            'email'=>'n\'est pas une adresse email valide!',
                            'notempty'=>'ne peut être vide!',
                            'accepted'=>'n\'est pas une reponse valide',
                            'notnull'=>'ne peut être null!',
                            'integer'=>'doit être de type entier!',
                            'float'=>'doit être un nombre à virgule flottante!',
                            'regex'=>'ne verifie pas les critères de validité souhaitées!',
                            'ip'=>'n\'est pas une adresse IP valide!',
                            'url'=>'n\'est pas une url valide!',
                            'range'=>'n\'est pas compris dans l\'intervalle souhaité!',
                            'date'=>'n\'est pas une date valide!',
                            'time'=>'n\'est pas une heure valide!',
                            'datetime'=>'n\'est pas de type Date et Heure valide!',
                            'bool'=>'doit être de type Booléen!',
                            'money'=>'doit être de type monétaire!',
                            'natnumber'=>'doit être un entier naturel!',
                            'hostname'=>'n\'pas un nom de domaine valide!',
                            'digits'=>'doit être un chiffre!',
                            'alnum'=>'ne doit contenir que des chiffres et des lettres!',
                            'alpha'=>'ne doit contenir que des caractères alphabétiques!',
                            'hex'=>'doit être de type hexadécimal!',
                            'numeric'=>'doit être un nombre!',
                            'ccnum'=>'n\'est pas un numéro de carte de credit valide!',
                            'fullname'=>'est soit trop court, soit il contient des caractères non autorisés.',
                            'subject'=>'est soit trop court, soit il contient des caractères non autorisés.',
                            'file'=>'n\'est pas un type de fichier autorisé sur ce site!',
                            'image'=>'doit être une image!',
                            'inlist'=>'n\'est pas un élement de la source des données à valider!',
                            'luhn'=>'ne verifie pas l\'algorithme de Luhn!',
                            'numcompare'=>'ne verifie pas les critères de validation souhaités'
                            );
/**
* constructeur de classe
*
**/ 
public function __construct($src = null)
{
    $this->origin = isset($src)? $src : ((strcmp($_SERVER'REQUEST_METHOD'],'POST')==0)? $_POST : $_GET) ;
    $this->reserved = array('origin','reserved','erroMsg','isValid');
}
/**
 * Reset internal variables for another validation run.
 *
 * @return void
 */
private function resetObjectVars()
{
    $properties = get_object_vars($this);
    foreach($properties as $k=>$v)
    {
    if($this->isInlist($k,$this->reserved)) continue;
    $this->$k = null;   
    }
}
/**
 * check internal variables which are not null
 *
 * @return void
 */
private function hasObjectVars()
{
    $properties = get_object_vars($this);
    foreach($properties as $k=>$v)
    {
    if($this->isInlist($k,$this->reserved)) continue;
    if($this->isNotempty($this->$k)) return true;   
    }
    return false;
}
/**
*
*
**/
public function isValid($rank,$fieldname,$type)
{   
    $this->resetObjectVars();//reset internal variables
    $this->field = $fieldname;
    if(!$this->isInlist($this->field,$this->origin))
    {
        $this->message = sprintf('Le champs %s n\'est pas un élement de la source des données à valider!',$this->field);
        return false;
    }
    if(is_array($type) or !$this->isNumeric($rank))
    {
        $attributes = $type;
        $type = $rank;
        $found = false;
        if(is_array($attributes))
        {
        $attributes=array_shift(array_map('strtolower',array_shift($attributes)));
            if(isset($attributes'min'])) $this->min=$attributes'min'];
            if(isset($attributes'max'])) $this->max=$attributes'max'];
            if(isset($attributes'to'])) $this->to=$attributes'to'];
            if(isset($attributes'format'])) $this->format=$attributes'format'];
            if(isset($attributes'rel'])) $this->rel=str_replace(array(' ', "\t", PHP_EOL, "\r", "\0", "\x0B"), '', strtolower($attributes'rel']));      
        }
    }
    $type = strtolower($type);
    $method = 'is'.ucfirst($type);
    if(!$this->isInlist($method,get_class_methods($this)) or $this->isInlist($method,$this->reserved))
    {
        $this->message = sprintf('La methode de validation du champs %s est introuvable. Impossible de completer la validation!',$this->field);
        return false;
    }
    $this->message = $this->getMessage($type);
    if(!isset($attributes) or $this->hasObjectVars())
    return $this->$method($this->origin->$fieldname);
    return $this->$method($this->origin->$fieldname,$attributes);
}
private function getMessage($type)
{
    $message = 'Le champs ';
    switch($type)
    {
        case 'range':
        case 'lenrange':
        if($type==='lenrange')$message .= sprintf('%s doit avoir au moins %s caracteres et au plus %s',$this->field,$this->min,$this->max);
        else $message .= sprintf('%s doit avoir une valeur comprise entre %s et %s',$this->field,$this->min,$this->max);
        break;
        case 'datacompare':
        $equal = array('=','==','===','equal');
        if(!$this->isInlist($this->rel,$equal))$message .= sprintf('%s ne peut être identiques à %s!',$this->field,$this->to);
        else $message .= sprintf('%s et %s ne sont pas identiques!',$this->field,$this->to);
        break;
        default:
        $message .= sprintf('%s %s',$this->field,$this->isInlist($type,array_keys($this->errorMsg))? $this->errorMsg$type] : 'est invalide');
        break;                      
    }
return $message;
}
    /**
     * Check for HTML field validity (no XSS please !)
     *
     * @param string $var HTML field to validate
     * @return boolean Validity is ok or not
     */
    private function isText($var)
    {
        $events = 'onmousedown|onmousemove|onmmouseup|onmouseover|onmouseout|onload|onunload|onfocus|onblur|onchange';
        $events .= '|onsubmit|ondblclick|onclick|onkeydown|onkeyup|onkeypress|onmouseenter|onmouseleave|onerror|onselect|onreset|onabort|ondragdrop|onresize|onactivate|onafterprint|onmoveend';
        $events .= '|onafterupdate|onbeforeactivate|onbeforecopy|onbeforecut|onbeforedeactivate|onbeforeeditfocus|onbeforepaste|onbeforeprint|onbeforeunload|onbeforeupdate|onmove';
        $events .= '|onbounce|oncellchange|oncontextmenu|oncontrolselect|oncopy|oncut|ondataavailable|ondatasetchanged|ondatasetcomplete|ondeactivate|ondrag|ondragend|ondragenter|onmousewheel';
        $events .= '|ondragleave|ondragover|ondragstart|ondrop|onerrorupdate|onfilterchange|onfinish|onfocusin|onfocusout|onhashchange|onhelp|oninput|onlosecapture|onmessage|onmouseup|onmovestart';
        $events .= '|onoffline|ononline|onpaste|onpropertychange|onreadystatechange|onresizeend|onresizestart|onrowenter|onrowexit|onrowsdelete|onrowsinserted|onscroll|onsearch|onselectionchange';
        $events .= '|onselectstart|onstart|onstop';
        return (!preg_match('/< \t\n]*script/ims', $var) && !preg_match('/('.$events.') \t\n]*=/ims', $var) && !preg_match('/.*script\:/ims', $var) && !preg_match('/< \t\n]*i?frame/ims', $var));
    }

    /**
     * Validate SIRET Code
     * @static
     * @param $var SIRET Code
     * @return boolean Return true if is valid
     */
    private function isSiret($var)
    {
        if (strlen($var) != 14)
            return false;
        $sum = 0;
        for ($i = 0; $i != 14; $i++)
        {
            $tmp = ((($i + 1) % 2) + 1) * intval($var$i]);
            if ($tmp >= 10)
                $tmp -= 9;
            $sum += $tmp;
        }
        return ($sum % 10 === 0);
    }
    /**
     * Validate APE Code
     * @static
     * @param $ape APE Code
     * @return boolean Return true if is valid
     */
    private function isApe($ape)
    {
        return (bool)preg_match('/^[0-9]{3,4}[a-zA-Z]{1}$/s', $ape);
    }
    /**
     * Price display method validity
     *
     * @param string $data Data to validate
     * @return boolean Validity is ok or not
     */
    private function isString($data)
    {
        return is_string($data);
    }   
    /**
     * Customization fields' label validity
     *
     * @param string $label
     * @return boolean Validity is ok or not
     */
    private function isLabel($label)
    {
        return (preg_match('/^^{}<>]*$/u', $label));
    }
    /**
     * Check for standard name file validity
     *
     * @param string $name Name to validate
     * @return boolean Validity is ok or not
     */
    private function isFilename($name)
    {
        return preg_match('/^[a-zA-Z0-9_.-]+$/', $name);
    }
    /**
     * Check for standard name directory validity 
     * 
     * @param string $dir Directory to validate
     * @return boolean Validity is ok or not
     */
    private function isDirname($dir)
    {
        return (bool)preg_match('/^[a-zA-Z0-9_.-]*$/', $dir);
    }
    /**
     * Check if URL is absolute
     *
     * @param string $url URL to validate
     * @return boolean Validity is ok or not
     */
    private function isAbsurl($url)
    {
        if (!empty($url))
            return preg_match('/^https?:\/\/,:#%&_=\(\)\.\? \+\-@\/a-zA-Z0-9]+$/', $url);
        return true;
    }
    /**
     * Check tracking number validity (disallowed empty string)
     *
     * @param string $var Tracking number to validate
     * @return boolean Validity is ok or not
     */
    private function isTracking($var)
    {
        return preg_match('/^~:#,%&_=\(\)\.\? \+\-@\/a-zA-Z0-9]+$/', $var);
    }
    /**
     * Check object validity
     *
     * @param integer $object Object to validate
     * @return boolean Validity is ok or not
     */
    private function isColor($var)
    {
        return preg_match('/^(#[0-9a-fA-F]{6}|[a-zA-Z0-9-]*)$/', $var);
    }
    /**
     * Check for an percentage validity (between 0 and 100)
     *
     * @param float $value Float to validate
     * @return boolean Validity is ok or not
     */
    private function isPercent($value)
    {
        return ($this->isFloat($value) && $value >= 0 && $value <= 100);
    }
        /**
     * Check for postal code validity
     *
     * @param string $var Postal code to validate
     * @return boolean Validity is ok or not
     */
    private function isPostcode($var,$country = 'fr')
    {
                $country = strtolower($country);
            switch ($country) {
                case 'uk':
                $regex = '/\\A\\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\\b\\z/i';
                break;
                case 'ca':
                $regex = '/\\A\\b[ABCEGHJKLMNPRSTVXY][0-9][A-Z] [0-9][A-Z][0-9]\\b\\z/i';
                break;
                case 'it':
                $regex = '/^(V-|I-)?[0-9]{5}$/i';
                break;
                case 'de':
                $regex = '/\b((?:0[1-46-9]\d{3})|(?:[1-357-9]\d{4})|(?:[4][0-24-9]\d{3})|(?:[6][013-9]\d{3}))\b/i';
                break;
                case 'fr':
                $regex = '/^(F-)?((2[A|B])|[0-9]{2})[0-9]{3}$/i';
                break;
                case 'be':
                $regex = '/^[1-9]{1}[0-9]{3}$/i';
                break;
                case 'us':
                $regex = '/\\A\\b[0-9]{5}(?:-[0-9]{4})?\\b\\z/i';
                break;
                case 'au':
                $regex = '/^(0[289][0-9]{2})|([1345689][0-9]{3})|(2[0-8][0-9]{2})|(290[0-9])|(291[0-4])|(7[0-4][0-9]{2})|(7[8-9][0-9]{2})$/i';
                break;
                case 'nl':
                $regex = '/^[1-9][0-9]{3}\s?([a-zA-Z]{2})?$/i';
                break;
                case 'es':
                $regex = '/^([1-9]{2}|[0-9][1-9]|[1-9][0-9])[0-9]{3}$/i';
                break;
                case 'dk':
                $regex = '/^([D-d][K-k])?( |-)?[1-9]{1}[0-9]{3}$/i';
                break;
                case 'se':
                $regex = '/^(s-|S-){0,1}[0-9]{3}\s?[0-9]{2}$/i';
                break;
                default:
                $regex = '/^[a-zA-Z 0-9-]+$/';
                break;                                                                              
            }
        return !$this->isNotempty($var) || $this->isRegex($var,$regex);
    }
        /**
     * Check for zip code format validity
     *
     * @param string $var zip code format to validate
     * @return boolean Validity is ok or not
     */
    private function isZipcode($var)
    {
        if (!empty($var))
            return preg_match('/^[NLCnlc 0-9-]+$/', $var);
        return true;
    }
        /**
     * Check for phone number validity
     *
     * @param string $var Phone number to validate
     * @return boolean Validity is ok or not
     */
    private function isPhone($var)
    {
        $regex = '/^+0-9. ()-]*$/';
        return $this->isRegex($var,$regex);
    }
    /**
     * Check for barcode validity (EAN-13)
     *
     * @param string $ean13 Barcode to validate
     * @return boolean Validity is ok or not
     */
    private function isEan13($ean13)
    {
        return !$ean13 || preg_match('/^[0-9]{0,13}$/', $ean13);
    }
    /*
     * Check for birthDate validity
     *
     * @param string $var birthdate to validate
     * @return boolean Validity is ok or not
     */
    private function isBirthdate($var)
    {
        if (empty($var) || $var == '0000-00-00')
            return true;
        if (preg_match('/^([0-9]{4})-((?:0?[1-9])|(?:1[0-2]))-((?:0?[1-9])|(?:[1-2][0-9])|(?:3[01]))([0-9]{2}:[0-9]{2}:[0-9]{2})?$/', $var, $birth_date))
        {
            if ($birth_date[1] > date('Y') && $birth_date[2] > date('m') && $birth_date[3] > date('d'))
                return false;
            return true;
        }
        return false;
    }
    /**
     * Check for a postal address validity
     *
     * @param string $var Address to validate
     * @return boolean Validity is ok or not
     */
    private function isAddress($var)
    {
        return !$this->isNotempty($var) || preg_match('/^^!<>?=+@{}_$%]*$/u', $var);
    }
    /**
     * Check for city name validity
     *
     * @param string $city City name to validate
     * @return boolean Validity is ok or not
     */
    private function isCityname($city)
    {
        $regex = '/^^!<>;?=+@#"°{}_$%]*$/u';
        return $this->isRegex($var,$regex);
    }
    /**
     * Check for search query validity
     *
     * @param string $var Query to validate
     * @return boolean Validity is ok or not
     */
    private function isSearch($var)
    {
        $regex = '/^^<>;=#{}]{0,64}$/u';
        return $this->isRegex($var,$regex);
    }

/**
 * Validates the email
 * 
 * @return boolean true on success, false on failure.
 */
private function isEmail($var,$deep=false)
{   
        $return = filter_var($var, FILTER_VALIDATE_EMAIL) ? true : false;
        if ($deep === false or $deep === null) return $return;
        if ($return === true && preg_match('/@((?:[a-z0-9]-a-z0-9]*\.)*(?:[a-z0-9]-a-z0-9]{0,62})\.(?:(?:[a-z]{2}\.)?[a-z]{2,4}|museum|travel))$/i', $var, $regs)) {
            if (function_exists('getmxrr') && getmxrr($regs[1], $mxhosts)) return true;
            if (function_exists('checkdnsrr') && checkdnsrr($regs[1], 'MX')) return true;
            return is_array(gethostbynamel($regs[1]));
        }
        return false;   
}   
/**
 * Validates a not empty value
 * Returns true if string contains something other than whitespace
 *
 * @return boolean true on success, false on failure.
 */
private function isNotempty($var)
{   
    if(!$this->isNotnull($var)) return false;
    $var = trim($var);
    if($var instanceof File)
    {
        return ((string) $var->getPath() != '')? true : false;  
    }
    if (empty($var) && $var != '0') return false;
    $regex = '/^\s]+/m';
    return $this->isRegex($var,$regex)? true : false;
}
    /**
     * Validate that an attribute was "accepted".
     *
     * This validation rule implies the attribute is "required".
     *
     * @param string $attribute
     * @param mixed $value
     * @return bool
     */
    private function isAccepted($var)
    {
        $var = strtolower($var);
        $acceptable = array('yes', 'on', 1);
        return ($this->isNotempty($var) and $this->isInlist($var, $acceptable))? true : false;
    }           
/**
 * Validates a not null value
 * 0 will pass.
 *
 * @return boolean true on success, false on failure.
 */
private function isNotnull($var)
{
    return (null != $var) ? true : false;
}       
/**
 * Validates an integer value
 * 
 * @return boolean true on success, false on failure
 */
private function isInteger($var)
{
    return (0 == $var || filter_var($var, FILTER_VALIDATE_INT)) ? true : false;
}       
/**
 * Validates a float value
 * 
 * @return boolean true on success, false on failure
 */
private function isFloat($var)
{   
    return (filter_var($var, FILTER_VALIDATE_FLOAT)) ? true : false;
}       
/**
 * Validates the element against the regexp
 * 
 * @return boolean true on success, false on failure
 */
private function isRegex($var,$regex)
{   
    return (preg_match($regex, $var)) ? true : false;
}   
/**
 * Validates an IP address
 * 
 * @return boolean true on success, false on failure
 */
private function isIp($var)
{   
    return IrivenCMS::isvalidIp($var);
}       
/**
 * Validates an url
 * 
 * @return Boolean true if url is valid, false otherwise
 */
private function isUrl($var, $valid=false)
{   
    if(!filter_var($var, FILTER_VALIDATE_URL)) return false;
    $url = str_replace(array('http://', 'https://', 'ftp://'), '', strtolower($var));
    if($valid and function_exists('checkdnsrr')) return checkdnsrr($url);
    return true;
}           
    /**
     * Check for date validity
     *
     * @param string $var Date to validate
     * @return boolean Validity is ok or not
     */
    private function isDate($var)
    {
        if (!preg_match('/^([0-9]{4})-((?:0?[0-9])|(?:1[0-2]))-((?:0?[0-9])|(?:[1-2][0-9])|(?:3[01]))( [0-9]{2}:[0-9]{2}:[0-9]{2})?$/', $var, $matches))
            return false;
        return checkdate((int)$matches[2], (int)$matches[3], (int)$matches[1]);
    }
/**
 * Time validation, determines if the string passed is a valid time.
 * Validates time as 24hr (HH:MM) or am/pm ([H]H:MM[a|p]m)
 * Does not allow/validate seconds.
 *
 * @param string $var a valid time string
 * @return boolean Success
 */
private function isTime($var)
{   
    $regex='%^((0?[1-9]|1[012])(:[0-5]\d){0,2} ?([AP]M|[ap]m))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$%';
    return $this->isRegex($var, $regex);
}
/**
 * Validates a datetime value
 * All values matching the "date" core validation rule, and the "time" one will be valid
 *
 * @param array $var Value to check
 * @param string|array $this->format Format of the date part
 * Use a string or an array of the keys below. Arrays should be passed as array('dmy', 'mdy', etc)
 * ## Keys:
 *
 *  - dmy 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash
 *  - mdy 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash
 *  - ymd 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash
 * - dMy 27 December 2006 or 27 Dec 2006
 *  - Mdy December 27, 2006 or Dec 27, 2006 comma is optional
 *  - My December 2006 or Dec 2006
 * - my 12/2006 separators can be a space, period, dash, forward slash
 * @param string $regex Regex for the date part. If a custom regular expression is used this is the only validation that will occur.
 * @return boolean True if the value is valid, false otherwise
 * @see Validation::date
 * @see Validation::time
 */
private function isDatetime($var)
{
    $valid = false;
    $parts = explode(' ', $var);
    if (!empty($parts) && count($parts) > 1)
    {
        $time = array_pop($parts);
        $var = implode(' ', $parts);
        $valid = $this->isDate($var) && $this->isTime($time);
    }
    return $valid;
}
/**
 * Boolean validation, determines if value passed is a boolean integer or true/false.
 *
 * @param string $var a valid boolean
 * @return boolean Success
 */
private function isBool($var)
{       
    $booleanList = array(0, 1, '0', '1', true, false);
    return in_array($var, $booleanList, true);
}
/**
 * Checks that a value is a monetary amount.
 *
 * @param string $var Value to check
 * @param string $symbolPosition Where symbol is located (left/right)
 * @return boolean Success
 */
private function isPrice($var)
{       
    $money = '(?!0,?\d)(?:\d{1,3}(?:(, .])\d{3})?(?:\1\d{3})*|(?:\d+))((?!\1),.]\d{2})?';
    $regex1 = $money . '(?<!\x{00a2})\p{Sc}?'; //symbol right
    $regex2 = '(?!\x{00a2})\p{Sc}?' . $money;//symbol left
    $regex = '/^('.$regex1.')|('.$regex2.')$/u';
    return $this->isRegex($var, $regex);
}
/**
 * Checks if a value is a natural number.
 *
 * @param string $var Value to check
 * @param boolean $allowZero Set true to allow zero, defaults to false
 * @return boolean Success
 * @see http://en.wikipedia.org/wiki/Natural_number
 */
private function isNatnumber($var, $allowZero = false)
{       
    $regex = $allowZero ? '/^(?:0|[1-9][0-9]*)$/' : '/^[1-9][0-9]*$/';
    return $this->isRegex($var, $regex);
}
/**
*
*
**/
private function isHostname($var)
{       
    $regex = '/(?:[a-z0-9]-a-z0-9]*\.)*(?:[a-z0-9]-a-z0-9]{0,62})\.(?:(?:[a-z]{2}\.)?[a-z]{2,4}|museum|travel)$/i';
    return $this->isRegex($var, $regex);    
}
 /**
 * Returns true if every character is a digit, false otherwise.
 * This is just like isInt(), except there is no upper limit.
 *
 * @param mixed $var
 * @return boolean
 *
 * @tag validator
 *
 * @assert('1029438750192730t91740987023948') === false
 * @assert('102943875019273091740987023948') === true
 * @assert(102943875019273091740987023948) === false
 */
private function isDigits($var)
{
    return ctype_digit((string) $var)? true : false;
}
/**
 * Checks that a string contains only integer or letters
 *
 * Returns true if string contains only integer or letters
 *
 * $var can be passed as an array:
 *
 * @param string|array $var Value to check
 * @return boolean Success
 */
private function isAlnum($var)
{       
    if (empty($var) && $var != '0') return false;
    return ctype_alnum($var)? true : false; 
}
/**
 * Returns true if every character is alphabetic, false
 * otherwise.
 *
 * @param mixed $var
 * @return boolean
 *
 * @tag validator
 *
 * @assert('NCOFWIERNVOWIEBHV12047057y0650ytg0314') === false
 * @assert('NCOFWIERNVOWIEBHV2@12047057y0650ytg0314') === false
 * @assert('funkatron') === true
 * @assert('funkatron_user') === false
 * @assert('funkatron-user') === false
 * @assert('_funkatronuser') === false
 */
private function isAlpha($var)
{       
    return ctype_alpha($var)? true : false;
}
/**
 * Returns true if value is a valid hexadecimal format, false
 * otherwise.
 *
 * @param mixed $var
 * @return boolean
 *
 * @tag validator
 *
 * @assert('6F') === true
 * @assert('F6') === true
 *
 */
private function isHex($var)
{       
    return ctype_xdigit($var)? true : false;
}   
/**
 * Checks if a value is numeric.
 *
 * @param string $var Value to check
 * @return boolean Success
 */
private function isNumeric($var)
{
    return is_numeric($var)? true : false;
}
/**
 * Validation of credit card numbers.
 * Returns true if $var is in the proper credit card format.
 *
 * @param string|array $var credit card number to validate
 * @param string|array $type 'all' may be passed as a sting, defaults to fast which checks format of most major credit cards
 * if an array is used only the values of the array are checked.
 * Example: array('amex', 'bankcard', 'maestro')
 * @return boolean Success
 */
private function isCcnum($var, $type = 'fast') {
    $var = str_replace(array('-', ' '), '', $var);
    if (mb_strlen($var) < 13) {
        return false;
    }
    $cards = array(
        'all' => array(
            'amex' => '/^3[4|7]\\d{13}$/',
            'bankcard'  => '/^56(10\\d\\d|022[1-5])\\d{10}$/',
            'diners'    => '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/',
            'disc' => '/^(?:6011|650\\d)\\d{12}$/',
            'electron'  => '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/',
            'enroute'   => '/^2(?:014|149)\\d{11}$/',
            'jcb' => '/^(3\\d{4}|2100|1800)\\d{11}$/',
            'maestro'   => '/^(?:5020|6\\d{3})\\d{12}$/',
            'mc' => '/^5[1-5]\\d{14}$/',
            'solo' => '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/',
            'switch'    => '/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4][0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/',
            'visa' => '/^4\\d{12}(\\d{3})?$/',
            'voyager'   => '/^8699[0-9]{11}$/'
        ),
        'fast' => '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/'
    );
    if (is_array($type)) {
        foreach ($type as $value) {
            $regex = $cards'all'][strtolower($value)];
            if ($this->isRegex($var, $regex)) {
                return $this->isLuhn($var);
            }
        }
    } elseif ($type == 'all') {
        foreach ($cards'all'] as $regex) {
            if ($this->isRegex($var, $regex)) {
                return $this->isLuhn($var);
            }
        }
    } else {
        $regex = $cards'fast'];
        if ($this->isRegex($var, $regex)) {
            return $this->isLuhn($var);
        }
    }
    return false;
}
/**
*
*
**/ 
private function isFullname($var,$max=null)
{
    if(isset($max) and $this->isNumeric($max)) $this->max = intval($max);
    if( !isset($this->max) or !$this->isNumeric($this->max)) $this->max = 40;
    $regex = '/^(:alpha:]]+(\-\' ]:alpha:]]+)*){4,'.$this->max.'}$/';
    return $this->isRegex($var, $regex);
}
/**
*
*
**/
private function isSubject($var,$max=null)
{
    if(isset($max) and $this->isNumeric($max)) $this->max = intval($max);
    if( !isset($this->max) or !$this->isNumeric($this->max)) $this->max = 60;
    $regex = '/^(:alpha:]\-_!?\',.: ]+){8,'.$this->max.'}$/';
    return $this->isRegex($var, $regex);
}
/**
 * Check that value has a valid file extension.
 *
 * @param string|array $var Value to check
 * @param array $extensions file extensions to allow.
 * @return boolean Success
 */
private function isFile($var, $ext) {
    if(!is_array($ext)) $ext = explode(',',$ext);
    $extension = strtolower(pathinfo($var, PATHINFO_EXTENSION));
    if ($this->isInlist($fileExt,$ext)) return true;
    return false;
}
/**
 * Check that value is a picture.
 *
 * @param string|array $var Value to check
 * @param array $extensions file extensions to allow. By default extensions are 'gif', 'jpeg', 'png', 'jpg'
 * @return boolean Success
 */
private function isImage($var){
    $ext = array('gif', 'jpeg', 'png', 'jpg','bmp');
    return $this->isFile($var, $ext);
}
/**
 * Field has to be one of the allowed ones.
 *
 * @param string|array $list Allowed values.
 * @param string $message
 * @return FormValidator
 */
private function isInlist($var,$list)
{       
    if(is_object($list)) return (isset($list->$var))? true : false;
    if (is_string($list)) {
        $list = explode(',', $list);
    }
    return in_array($var, $list)? true : false;
}
/**
 * Luhn algorithm
 *
 * @param string|array $var
 * @return boolean Success
 * @see http://en.wikipedia.org/wiki/Luhn_algorithm
 */
private function isLuhn($var)
{
    if ($var == 0) {
        return false;
    }
    $sum = 0;
    $length = strlen($var);
    for ($position = 1 - ($length % 2); $position < $length; $position += 2) {
        $sum += $var$position];
    }
    for ($position = ($length % 2); $position < $length; $position += 2) {
        $var = $var$position] * 2;
        $sum += ($var < 10) ? $var : $var - 9;
    }
    return ($sum % 10 == 0);
}
/**
 * Used to compare 2 numeric values.
 *
 * @param string|array $var if string is passed for a string must also be passed for $this->to
 * used as an array it must be passed as array('check1' => value, 'operator' => 'value', 'check2' -> value)
 * @param string $this->rel Can be either a word or operand
 * is greater >, is less <, greater or equal >=
 * less or equal <=, is less <, equal to ==, not equal !=
 * @param integer $this->to only needed if $var is a string
 * @return boolean Success
 */
    private function isNumcompare($var,$to=null, $rel=null) {
        if(!isset($this->to)) $this->to = $to;
        if(!$this->isNumeric($var) or !$this->isNumeric($this->to)) return false;
        switch ($this->rel) {
            case 'greater':
            case '>':
                return ($var > $this->to)? true: false;
                break;
            case 'less':
            case '<':
                return ($var < $this->to)? true: false;
                break;
            case 'greaterwith':
            case '>=':
                return($var >= $this->to)? true: false;
                break;
            case 'lesswith':
            case '<=':
                return($var <= $this->to)? true: false;
                break;
            case 'different':
            case 'notequal':
            case '!=':
            case '!==':
            case '<>':
                return ($var != $this->to)? true: false;
                break;
            default:
                return($var == $this->to)? true: false;
                break;
        }
    }
/**
 * Checks whether the length of a string is greater or equal to a minimal length.
 *
 * @param string $var The string to test
 * @param integer $this->min The minimal string length
 * @return boolean Success
 */
private function isLencompare($var,$to) 
{   
    if(!isset($this->to)) $this->to = $to;
    if($this->isInlist($this->to,$this->origin)) 
    return $this->isNumcompare(mb_strlen($var),mb_strlen($this->origin->$this->to));
    if(!$this->isNumeric($this->to)) return false;
    return $this->isNumcompare(mb_strlen($var),$this->to);
}
/**
 * Validate that a number is in specified range.
 * if $lower and $upper are not set, will return true if
 * $var is a legal finite on this platform
 *
 * @param string $var Value to check
 * @param integer $lower Lower limit
 * @param integer $upper Upper limit
 * @return boolean Success
 */
private function isRange($var)
{   
    if(!isset($this->min) or !isset($this->max)) return false;
    if (!is_numeric($var)) return false;
    $this->rel = '<';   
    if($this->isNumcompare($var,$this->min)) return false;
    $this->rel = '>';
    if($this->isNumcompare($var, $this->max)) return false; 
    return true;

}   
/**
 * Field has to be between minlength and maxlength characters long.
 *
 * @param int $this->minlength
 * @param int $this->maxlength
 * @
 */
private function isLenrange($var)
{   
    if(!isset($this->min) or !isset($this->max)) return false; 
    $this->rel = '<';   
    if($this->isLencompare($var,$this->min)) return false;
    $this->rel = '>';
    if($this->isLencompare($var, $this->max)) return false; 
    return true;
}   
/**
 * Check that value is exactly $comparedTo.
 *
 * @param mixed $var Value to check
 * @param mixed $comparedTo Value to compare
 * @return boolean Success
 */
private function isDatacompare($var, $to) 
{   if(!isset($this->to)) $this->to = $to;
    if($this->isNumeric($var) and $this->isNumeric($this->to)) return $this->isNumcompare($var,$this->to);
    if($this->isInlist($this->to,$this->origin)) $this->to = $this->origin->$this->to;
    switch($this->rel)
    {
        case 'different':
        case 'notequal':
        case '!=':
        case '!==':
        case '<>':
        return ($var !== $this->to)? true:false;
        break;
        default:
        return ($var === $this->to)? true : false;
        break;
    }
}
}

2 réponses


iriven
Auteur

pour faire simple, chaque cle du tableau (attribut) $errorMsg constitue une methode de validation.
soit ce formulaire de contact: http://www.iriven.com/contact
pour le valider on pourra proceder coe suit:

<?php // Direct calls to this file are Forbidden when core files are not present
class Contact extends Model{
var $validate = array(
                        'name'=>array('notempty','fullname'=>array('min'=>4,'max'=>30)),
                        'title'=>array('notempty','subject'=>array('min'=>8,'max'=>60)),
                        'email'=>array('notempty','email'),                                             
                        'message'=>array('notempty','text'),                        
                        'captcha'=>array('notempty','regex'=>'/^[0-9]{1,2}$/')                      
                        );

/**
* End of the class
*
**/ 
}

Bonne initiative je voulais en faire un aussi de Helper pour la validation des données le tien a l'air très complet néanmoins je ne vois pas l'utilité de certaines règles (hexa,booléen etc...) je doute que pour la validation d'un formulaire c'est le genre d'information que tu devras renseigner ^^ .

Après j'ai pas regardé tout ce qu'il y avait mais une règle de confirmation est assez importante. En effet lorsque tu t'inscris sur les sites on te demande souvent de confirmer ton mot de passe etc ;) .