-3

My string always looks like this:

04.01.2018 - 20.01.2018

So the pattern is: d.m.Y - d.m.Y

I thought REGEX would be the first choice. Comments says not to use REGEX.

Any suggestions on how to validate it?

Terminus
  • 71
  • 6

1 Answers1

1

Regex is definitely not the way. Split the string, and use a date-based method to validate each date.

Code: (Demo)

function valiDate($date,$format='d.m.Y'){
    $d=DateTime::createFromFormat($format,$date);
    return $d && $d->format($format)==$date;
}

function regex($date){
    return preg_match('/^\d{2}\.\d{2}\.\d{4} - \d{2}\.\d{2}\.\d{4}$/',$date);
}
/* or 
    function valiDate($date){
        $date=DateTime::createFromFormat('d.m.Y',$date);
        $date_errors=DateTime::getLastErrors();
        if($date_errors['warning_count'] || $date_errors['error_count']){
            return false;
        }
        return true;
    }
*/
// both valiDate functions from https://stackoverflow.com/questions/12030810/php-date-validation

$dateranges=[
    '04.01.2018 - 20.01.2018',
    '01.01.2017 - 01.02.201s',
    '00.00.0000 - 99.99.9999',
    "fish\t\t\t\t\t",
    '31.02.2018 - 31.03.2019',
    '12.13.2016 - 12.14.2016',
    '04.04.2018 - 04.04.2017'
];
foreach($dateranges as $daterange){  
    $dates=explode(' - ',$daterange,2);
    echo "($daterange}) ";
    echo 'valiDate: ',(isset($dates[1]) && valiDate($dates[0]) && valiDate($dates[1]))?'valid':'bonk';
    echo "\t-VS-\t";
    echo 'regex: ',regex($daterange)?'valid':'bonk';
    echo "\n";
}

Output:

(04.01.2018 - 20.01.2018}) valiDate: valid  -VS-    regex: valid
(01.01.2017 - 01.02.201s}) valiDate: bonk   -VS-    regex: bonk
(00.00.0000 - 99.99.9999}) valiDate: bonk   -VS-    regex: valid
(fish                   }) valiDate: bonk   -VS-    regex: bonk
(31.02.2018 - 31.03.2019}) valiDate: bonk   -VS-    regex: valid
(12.13.2016 - 12.14.2016}) valiDate: bonk   -VS-    regex: valid
(04.04.2018 - 04.04.2017}) valiDate: valid  -VS-    regex: valid

p.s. I added the isset() call to avoid Notices when two elements are not generated from explode().

mickmackusa
  • 43,625
  • 12
  • 83
  • 136