Classe form, gestion de validation pour formulaire

Soyez le premier à donner votre avis sur cette source.

Snippet vu 9 793 fois - Téléchargée 964 fois

Contenu du snippet

Une classe simple d'utilisation, qui permet de valider les données d'un formulaire et d'autoriser son envoi.

- Personnalisation des messages pour chaque types d'erreurs détectés.
- Gère les types : entiers, caractères ou selon vos attentes.
- Gère l'upload de fichier : types mimes, extensions, taille fichier, téléchargement.
- Utilisation des méthodes magiques, pour faciliter les accès aux données envoyés.

Source / Exemple :


<?php   
 
/**

  • Form class,
  • Check fields and data validity
  • @category classes
  • @author PHPANONYME
  • @license GNU/LGPL
  • /
/* Exception Handling */ class Form_Exception extends Exception { } class Form { /** @var array copy of $_POST or $_GET */ public $_method; /** @var array copy of $_FILES */ public $_file; /** @var array Save all errors of form */ public $_controller; public function __construct($method) { $this->_method = array(); $this->_controller = array(); $this->_file = (!empty($_FILES)) ? $_FILES : ''; if($method AND preg_match('/^(post|get)$/i', $method, $out)) $this->_method = ($out[1]==strtolower('post')) ? $_POST : $_GET; else throw new Form_Exception('Indicate the method used, with \'post\' or \'get\''); } /**
  • Check if we can transmit form
  • @param string $key key value
  • @param string $message message error
  • @return boolean Validity is not ok
  • /
public function sendForm() { return (!empty($this->_method) AND empty($this->_controller)) ? TRUE : FALSE; } /**
  • Return errors or an error with key
*
  • @param string $key key value
  • @param string $message message error
  • @return boolean Validity is not ok
  • /
public function getError($key = FALSE) { if($this->sendForm()) return false; if(empty($this->_method)) return false; if($key) return ($this->issetError($key)) ? $this->_controller[$key] : FALSE; return implode('<br/>', $this->_controller); } /**
  • Check if error exist with key
  • @param string $key key value
  • @return boolean Validity is not ok
  • /
public function issetError($key) { return (isset($this->_controller[$key]))? TRUE : FALSE; } /**
  • Save error with key
  • @param string $key key value
  • @param string $errorMessage message error
  • @return boolean Validity is not ok
  • /
public function setError($key, $errorMessage) { if(!empty($this->_controller[$key])) return false; if(is_array($errorMessage)) $errorMessage = implode('<br/>', $errorMessage); return $this->_controller[$key] = strval($errorMessage); } ////////////////////////////////////////////////////// // CONTROLLERS METHODS, used to control forms ////////////////////////////////////////////////////// /**
  • Checks if key exists for methods 'post' or 'get'
  • @param string $key key value
  • @param string $message message error
  • @param boolean $returnError indicates the return type, only a boolean or not
  • @return boolean Validity is not ok
  • /
public function issetValue($key, $message=NULL, $returnError=TRUE) { if (is_array($key)) { foreach($key AS $keyof => $value) { if(isset($this->_method[$keyof]) AND empty($this->_method[$keyof])) $this->setError($keyof, $value); } return; } if($returnError) return (isset($this->_method[$key]) AND empty($this->_method[$key])) ? $this->setError($key, $message) : FALSE; return (isset($this->_method[$key]) AND !empty($this->_method[$key])) ? TRUE : FALSE; } /**
  • Checks if key exists for methods 'files'
  • @param string $key key value
  • @param string $message message error
  • @param boolean $returnError indicates the return type, only a boolean or not
  • @return boolean Validity is not ok
  • /
public function issetFile($key, $message=NULL, $returnError=TRUE) { if (is_array($key)) { foreach($key AS $keyof => $value) { if(isset($this->_file[$keyof]) AND empty($this->_file[$keyof]['name'])) $this->setError($keyof, $value); } return; } if($returnError) return (isset($this->_file[$key]) AND empty($this->_file[$key]['name'])) ? $this->setError($key, $message) : FALSE; return (isset($this->_file[$key]) AND !empty($this->_file[$key]['name'])) ? TRUE : FALSE; } /**
  • Checks that these are only integers
  • @param string $key key value
  • @param string $message message error
  • @return boolean Validity is not ok
  • /
public function isInt($key, $message=NULL) { if (is_array($key)) { foreach($key AS $keyof => $value) { if(isset($this->_method[$keyof]) AND preg_match('/[^0-9]/', $this->_method[$keyof])) $this->setError($keyof, $value); } return; } return (isset($this->_method[$key]) AND preg_match('/[^0-9]/', $this->_method[$key])) ? $this->setError($key, $message) : FALSE; } /**
  • Checks that these are only characters
  • @param string $key key value
  • @param string $message message error
  • @return boolean Validity is not ok
  • /
public function isChar($key, $message = NULL) { if (is_array($key)) { foreach($key AS $keyof => $value) { if(isset($this->_method[$keyof]) AND preg_match('/[^a-z]/i', $this->_method[$keyof])) $this->setError($keyof, $value); } return; } return (isset($this->_method[$key]) AND preg_match('/[^a-z]/i', $this->_method[$key])) ? $this->setError($key, $message) : FALSE; } /**
  • Checks validity for email
  • @param string $key key value
  • @param string $message message error
  • @return boolean Validity is not ok
  • /
public function isEmail($key, $message=NULL) { $pattern = '/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/'; if (is_array($key)) { foreach($key AS $keyof => $value) { if(isset($this->_method[$keyof]) AND !preg_match($pattern, $this->_method[$keyof])) $this->setError($keyof, $value); } return; } return (isset($this->_method[$key]) AND !preg_match($pattern, $this->_method[$key])) ? $this->setError($key, $message) : FALSE; } /**
  • Checks the validity with a custom type
  • @param string $key key value
  • @param string $rules pattern customize
  • @param string $message message error
  • @return boolean Validity is not ok
  • /
public function isExtendType($key, $rules, $message=NULL) { if (is_array($key)) { foreach($key AS $keyof => $value) { if(isset($this->_method[$keyof]) AND preg_match($rules, $this->_method[$keyof])) $this->setError($keyof, $value); } return; } return (isset($this->_method[$key]) AND preg_match($rules, $this->_method[$key])) ? $this->setError($key, $message) : FALSE; } public function isNotExtendType($key, $rules, $message=NULL) { if (is_array($key)) { foreach($key AS $keyof => $value) { if(isset($this->_method[$keyof]) AND !preg_match($rules, $this->_method[$keyof])) $this->setError($keyof, $value); } return; } return (isset($this->_method[$key]) AND !preg_match($rules, $this->_method[$key])) ? $this->setError($key, $message) : FALSE; } /**
  • Verifies that a file has been transmitted
  • @param string $key key value
  • @param string $message message error
  • @return boolean Validity is not ok
  • /
public function isFileTransmit($key, $message=NULL) { if (is_array($key)) throw new Form_Exception('Do not use tables'); if(empty($this->_file[$key])) return false; $value = $this->issetFile($key, '', FALSE); return ($value AND ($this->_file[$key]['error']!=UPLOAD_ERR_OK OR !is_uploaded_file($this->_file[$key]['tmp_name'])) ) ? $this->setError($key, $message) : FALSE; } /**
  • Checks the validity of the extension for file
  • @param string $key key value
  • @param string or array $extensions extension file
  • @param string $message message error
  • @return boolean Validity is not ok
  • /
public function isFileExtensions($key, $extensions, $message=NULL) { if (is_array($key)) throw new Form_Exception('Do not use tables'); if(is_array($extensions)) $extensions = implode('|', $extensions); $value = $this->issetFile($key, '', FALSE); return ($value AND !preg_match('/('.$extensions.')$/i', $this->_file[$key]['name'])) ? $this->setError($key, $message) : FALSE; } /**
  • Checks the validity of the mime type for file
  • @param string $key key value
  • @param string or array $mimes mime type
  • @param string $message message error
  • @return boolean Validity is not ok
  • /
public function isFileMimes($key, $mimes, $message=NULL) { if (is_array($key)) throw new Form_Exception('Do not use tables'); if(is_array($mimes)) $mimes = implode('|', $mimes); $value = $this->issetFile($key, '', FALSE); if(version_compare(substr(phpversion(), 0, 3), '5.3.0') >= 0 OR !class_exists('finfo', false)) return ($value AND !preg_match('#^('.$mimes.')$#i', $this->_file[$key]['type'])) ? $this->setError($key, $message) : FALSE; elseif($value) { $finfo = new finfo; $realmime = $finfo->file($this->_file[$key]['tmp_name'], FILEINFO_MIME_TYPE); return (!preg_match('#^('.$mimes.')$#i', $realmime)) ? $this->setError($key, $message) : FALSE; } return false; } /**
  • Checks the validity of the size for file
  • @param string $key key value
  • @param int $size size file in octet
  • @param string $message message error
  • @return boolean Validity is not ok
  • /
public function isFileSize($key, $size, $message=NULL) { if (is_array($key) OR is_array($size)) throw new Form_Exception('Do not use tables'); if(preg_match('/[^0-9]/', $size)) throw new Form_Exception('Use only int values'); $value = $this->issetFile($key, '', FALSE); return ($value AND $size<=$this->_file[$key]['size']) ? $this->setError($key, $message) : FALSE; } /**
  • Checks the validity of comparing values
  • @param string $key key value
  • @param string $message message error
  • @return boolean Validity is not ok
  • /
public function compareValue($key, $value1, $value2, $sign=FALSE, $message=NULL) { $issetKey = $this->issetValue($key, '', FALSE); if(is_array($key)) throw new Form_Exception('Do not use tables'); if(is_array($value1) AND is_array($value2)) throw new Form_Exception('Only one of the two values may be in the form of a table'); if(!isset($value1) AND !isset($value2)) throw new Form_Exception('Indicate two values to compare'); if($sign AND !preg_match('/^(===|==|<=|>=|<>|!=|!==|<|>)$/', $sign)) throw new Form_Exception('Specify valid comparison operators'); // Operating if(is_array($value1) AND !is_array($value2)){ $value1 = implode('|', $value1); return ($issetKey AND preg_match('/^('.$value1.')$/', $value2)) ? FALSE : $this->setError($key, $message); } elseif(!is_array($value1) AND is_array($value2)){ $value2 = implode('|', $value2); return ($issetKey AND preg_match('/^('.$value2.')$/', $value1)) ? FALSE : $this->setError($key, $message); } elseif(empty($sign)) { return ($issetKey AND preg_match('/^('.$value1.')$/', $value2)) ? FALSE : $this->setError($key, $message); } else { $comparate = Form::getComparison($value1, $value2, $sign); return ($issetKey AND !$comparate) ? FALSE : $this->setError($key, $message); } } ////////////////////////////////////////////////////// // MAGICS METHODS ////////////////////////////////////////////////////// public function __get($key) { if(isset($this->_method[$key])) return $this->_method[$key]; elseif(isset($this->_file[$key])) return $this->_file[$key]['name']; else return false; } public function __isset($key) { if(isset($this->_method[$key])) return isset($this->_method[$key]); elseif(isset($this->_file[$key])) return isset($this->_file[$key]); } public function __unset($key) { if(isset($this->_method[$key])) unset($this->_method[$key]); if(isset($this->_file[$key])) unset($this->_file[$key]); } ////////////////////////////////////////////////////// // STATICS METHODS ////////////////////////////////////////////////////// public static function getComparison($value1, $value2, $sign) { switch($sign) { case '===' : return ($value1===$value2) ? TRUE : FALSE; break; case '!==' : return ($value1!==$value2) ? TRUE : FALSE; break; case '==' : return ($value1==$value2) ? TRUE : FALSE; break; case '<=' : return ($value1<=$value2) ? TRUE : FALSE; break; case '>=' : return ($value1>=$value2) ? TRUE : FALSE; break; case '<>' : case '!=' : return ($value1!=$value2) ? TRUE : FALSE; break; case '<' : return ($value1<$value2) ? TRUE : FALSE; break; case '>' : return ($value1>$value2) ? TRUE : FALSE; break; } } } ?>

A voir également

Ajouter un commentaire

Commentaires

Commenter la réponse de begueradj

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.