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:
preg_match('/^([0-9]{4})-([0-9]{2})$/', $expirationDate, $matches)
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 []
.
Use ^
and $
anchors:
if (!preg_match('/^([0-9]{4})\-([0-9]{2})$/', $expirationDate, $matches)) {
throw new Services_Payment_Exception('Card expiration date is invalid');
}
to ensure the whole string matches the pattern.
In your example 20111-02 matches because it matches the 0111-02
part of 20111-02
.
It's matching 0111-02
, which fits your requirements.
Change:
'/([0-9]{4})\-([0-9]{2})/'
to:
'/^([0-9]{4})\-([0-9]{2})$/'
so it only checks against the entirety of the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With