Lightweight Validator in PHP

Ziel war es, mit wenig Zeilen einen möglichst einfach zu verwendenden Validator zu schaffen, der sich zudem einfach erweitern lässt und ohne viele Abhängigkeiten auskommt. Daraus entstanden ist folgendes:

Anwendungsbeispiel:

//Anwendungsbeispiel
$oValidator = new Validator();

$oValidator->isValid("http://sklueh.de", 'url'); //true
$oValidator->isValid("http:/%$$^1sklueh.de", 'url');//false
$oValidator->isValid("http://sklueh.de", 'url|min_length[16]|max_length[20]|required'); //true
$oValidator->isValid("http://sklueh.de", 'url|min_length[17]|max_length[20]|required'); //false
$oValidator->isValid("http://sklueh.de", 'url|min_length[10]|max_length[15]|required'); //false
$oValidator->isValid("39.91", 'greater_than[39.90]'); //true
$oValidator->isValid("40", 'greater_than[39.90]'); //true
$oValidator->isValid("39.90", 'greater_than[39.90]'); //false
$oValidator->isValid('2', 'match[1,2]'); //true
$oValidator->isValid('3', 'match[1,2,5,7]'); //false
$oValidator->isValid('o_O?', 'match[lol,rofl,o_O?,lololol,l000000l]'); //true
$oValidator->isValid(md5('my_password'), 'equals['.md5('my_password').']'); //true
$oValidator->isValid(md5('my_password'), 'equals['.md5('my_wrong_password').']'); //false
$oValidator->isValid("1.1.2012", 'date'); //true
$oValidator->isValid("30.2.2012", 'date'); //false
$oValidator->isValid("2.2012", 'date'); //false

Validator
Diese Klasse kümmert sich um die Interpretation der Suchmuster.

class Validator
{
    public function isValid($mValue, $mPattern)
    {
        $aPatterns = explode("|", $mPattern);
       
        foreach( (array) $aPatterns as $sRule) //Alle definierten Regeln durchlaufen
        {
            $aRuleParams = $this->detachParams("[", "]", $sRule); //Zusätzliche Parameter von dem Regel-String lösen
            $oReflectionMethod = new ReflectionMethod($sValidationClass = "ValidatorRules", 'check_'.$sRule);
            if(!$oReflectionMethod->invoke(new $sValidationClass(), $mValue, $aRuleParams)) return false; //Methode für Validierung aufrufen
        } return true;
    }
   
    public function detachParams($cFirstChar, $cSecondChar, &$sRule)
    {
        preg_match_all("/\".$cFirstChar."(.*?)\".$cSecondChar."/", $sRule, $aMatches);
        $sRule = preg_replace("
/\\[(.*?)\\]/", "", $sRule);
        return $aMatches[1];
    }
}

Regeldefinitionen
Die Klasse „ValidatorRules“ enthält die Regeldefinitionen und kann nach Belieben erweitert werden.

class ValidatorRules
{
    public function check_required($mValue)
    {
        return (trim($mValue) === "" ? false : true);
    }
   
    public function check_min_length($mValue, $aParams)
    {
        return (strlen($mValue) >= $aParams[0]);
    }
   
    public function check_exact_length($mValue, $aParams)
    {
        return (strlen($mValue) == $aParams[0]);
    }

    public function check_max_length($mValue, $aParams)
    {
        return (strlen($mValue) <= $aParams[0]);
    }
   
    public function check_less_than($mValue, $aParams)
    {
        return (number_format($mValue, 15) < $aParams[0]);
    }
   
    public function check_greater_than($mValue, $aParams)
    {
        return (number_format($mValue, 15) > $aParams[0]);
    }
   
    public function check_alpha($mValue)
    {
        return ctype_alpha($mValue);
    }
   
    public function check_alpha_numeric($mValue)
    {
        return ctype_alnum($mValue);
    }
   
    public function check_integer($mValue)
    {
        return strval(intval($mValue)) === strval($mValue);
    }
   
    public function check_decimal($mValue)
    {
         return ($mValue == (string)(float)$mValue);
    }
   
    public function check_date($mValue)
    {
        if(!preg_match("/^\d{1,2}\.\d{1,2}\.\d{4}$/", $mValue)) return false;
        $aDateParts = explode('.', $mValue);
        return checkdate ( $aDateParts[1], $aDateParts[0] , $aDateParts[2]);
    }
   
    public function check_email($mValue)
    {
        return (filter_var( $mValue, FILTER_VALIDATE_EMAIL ) !== false ? true : false);
    }
   
    public function check_digits($mValue)
    {
        return ctype_digit($mValue);
    }
   
    public function check_url($mValue)
    {
        //Danke an David Müller (http://www.d-mueller.de)
        return ((strpos(trim($mValue), "http://") === 0 || strpos(trim($mValue), "https://") === 0) &&
                 filter_var(trim($mValue), FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED | FILTER_FLAG_HOST_REQUIRED) !== false);
    }
   
    public function check_equals($mValue, $aParams)
    {
        return ($mValue === $aParams[0]);
    }
   
    public function check_match($mValue, $aParams)
    {
        return in_array($mValue, explode(',', $aParams[0]));
    }
}

Für Anmerkungen und Verbesserungsvorschläge einfach einen Kommentar unter diesem Artikel hinterlassen – Danke. Der dargestellte Quellcode soll nur zur Inspiration dienen.

Download: lightweight-validation
GitHub: lightweight-validation

9 Gedanken zu „Lightweight Validator in PHP“

  1. Hi,

    Just read the source code fast and wanted to point out an enhancement.

    In your Validator class, the method isValid has a foreach. It should return false the first time the reflection result is false. Otherwise, it go on testing but it’s useless…

    However, thanks for sharing!

  2. Hi, Sebastian! Why aren’t You using static methods? There is no object features here, it is easier to access static methods globally and no need to create unnecesarry objects. 🙂

  3. Hey there! This is my 1st comment here so I just wanted to give a quick shout out and tell you I truly enjoy reading your blog posts.
    Can you recommend any other blogs/websites/forums that deal with the same topics?
    Thanks a lot!

  4. Hi there fantastic blog! Does running a blog like this require a great deal of work?
    I have very little understanding of computer programming however I was hoping
    to start my own blog in the near future. Anyways, if you have any ideas or tips for new blog owners please share.

    I know this is off topic but I simply wanted
    to ask. Appreciate it!

  5. It’s actually a nice and helpful piece of information. I am satisfied that you shared this useful info with us. Please keep us informed like this. Thank you for sharing.

Schreibe einen Kommentar