Prosta klasa do walidowania danych pochodzących od użytkownika.
<?php
/**
* Validator
*
* @author Strzałek
* @package Tellur
* @subpackage Model
* @version 1.0.0
*/
class Validator {
/**
* Bledy ktore wystpaia podczas
* walidacji danych
*
* @var array
*/
private $errors = array();
/**
* Stan walidacji
*
* @var bool
*/
private $valid = true;
/**
* Metoda sprawdzajaca dlugosc
*
* @param string $string
* @param int $min
* @param int $max
* @param string $error
* @return bool
*/
public function lenght($string, $min, $max, $error){
if($lenght > $min){
if($lenght < $max){
return true;
}else{
return $this -> setError($error);
}
}else{
return $this -> setError($error);
}
}
/**
* Metoda sprawdzajaca identycznosc
* dwoch stringow
*
* @param string $string1
* @param string $string2
* @param string $error
* @return bool
*/
public function same($string1, $string2, $error){
if($string1 == $string2){
return true;
}else{
return $this -> setError($error);
}
}
/**
* Sprawdzanie stringa wyrazeniem
* regularnym
*
* @param string $string
* @param string $regex
* @param string $error
* @return bool
*/
public function pattern($string, $regex, $error){
return true;
}else{
return $this -> setError($error);
}
}
/**
* Sprawdzanie czy zwalidowano
*
* @return bool
*/
public function isValid(){
return $this -> valid;
}
/**
* Ustawienie bledy walidacji
*
* @param string $message
* @return bool
*/
private function setError($message){
$this -> errors[] = $message;
return $this -> valid = false;
}
/**
* Zwrocenie tablicy z bledami
*
* @return array
*/
public function getErrors(){
return $this -> errors;
}
}
/* Przykład użycia */
$v = new Validator();
$v -> lenght('L', 2, 32, 'Login musi mieć od 2 do 32 liter');
$v -> same('moje1tajne2hasl', 'moje1tajne2haslo', 'Hasla nie sa identyczne');
$v -> pattern('heniek@ze-wsi.com', '#^[A-Za-z0-9._-]+@[[A-Za-z0-9.-]+$#', 'To nie jest poprawny adres email');
if($v -> isValid()){
//reestrujemy Heńka
}else{
var_dump($v -> getErrors
()); //wyswietlamy błedy ;) }
?>