Reputation: 6365
I'm trying to validate a date in dd-mm-yyyy format, where the year should be between 1900 to 2019.
The day and month part work fine, but i'm failing with the year part. Can you pls help?
$date="31-12-2020";
if (preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-(19[0-9]{2}|20([0-1]|[0-9]){2})$/",$date)) {
echo 'True';
return true;
} else {
echo 'False';
return false;
}
Upvotes: 0
Views: 1339
Reputation: 18357
Your current year part 20([0-1]|[0-9]){2}
for handling years 2000 to 2019 just needs little modification to make it correct. Third digit in year part can only be 0
or 1
hence it can be written as [01]
and fourth digit can be any hence can be written as [0-9]
and that gives us 20[01][0-9]
. Following is your modified regex you can use,
^(0[1-9]|[1-2][0-9]|3[0-1])-(0[1-9]|1[0-2])-(19[0-9]{2}|20[01][0-9])$
Also, since you're just validating your text, you can convert all groups as non-capturing groups to make it little better performance wise.
^(?:0[1-9]|[1-2][0-9]|3[0-1])-(?:0[1-9]|1[0-2])-(?:19[0-9]{2}|20[01][0-9])$
Upvotes: 0
Reputation: 507
This is complete script that you need; function will return true or false if given date is in range:
http://sandbox.onlinephpfunctions.com/code/c0e8108319a24ae5ecf993bb940e1f30aab53fc7
$start_date = '01-01-1900';
$end_date = '01-01-2019';
$date_from_user = '01-01-2018';
check_in_range($start_date, $end_date, $date_from_user);
function check_in_range($start_date, $end_date, $date_from_user,$format='d-m-Y')
{
// Convert to timestamp
$start_ts = DateTime::createFromFormat($format,$start_date);
$end_ts = DateTime::createFromFormat($format,$end_date);
$user_ts = DateTime::createFromFormat($format,$date_from_user);
// Check that user date is between start & end
return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
}
Upvotes: 5
Reputation: 2005
This think year expression should as below
19[0-9][0-9] | 20[0-1][0-9]
Upvotes: -1