I’m trying to use a modified preg format from preg_match: check birthday format (dd/mm/yyyy) to match credit card expiration dates (yyyy-MM formats)
if (!preg_match('/([0-9]{4})\-([0-9]{2})/', $expirationDate, $matches)) {
throw new Services_Payment_Exception('Card expiration date is invalid');
}
For some reason, it also validate invalid values such as 20111-02 (invalid year).
What am I doing wrong here? I want to confirm the year is 4 digits and the month is 2 digits (01, 02.. 12)
Anchor your regexp:
Your regexp didn’t do what you expected because it matches “0111-02” substring of “20111-02”.
Anchors
^and$match particular positions within the input string:^matches the beginning of the string and$matches the end.Note also that there is no need to escape the hyphen since it only has a special function in
[].