Search code examples
phpdatabasevalidationdate

Validate string input for DateTime::modify()


I have as scenario where the $string variable sent to DateTime::modify($string) is read from a database edited by users, how can i validate that $string is a proper string for DateTime::modify() ?


Solution

  • You could do something like this, and call it before you pass the string into your actual date:

    function modifyIsValid($modifyString) {
        $d = new DateTime();
        $isValid = $d->modify($modifyString);
    
        if ($isValid === false) {
            return false;
        }
    
        return true;
    }
    

    ->modify() returns false is the string passed is not valid, although it will also throw up an E_Warning which is not ideal.

    $d = new DateTime();
    $string = 'not a valid modifier';
    
    if (modifyIsValid($string)) {
        // Continue 
    }  else {
        // Print a friendly error message.
    }
    

    You can find more information about it in the manual: http://php.net/manual/en/datetime.modify.php

    Hope it helps.