5

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)

Community
  • 1
  • 1
aporat
  • 5,922
  • 5
  • 32
  • 54

5 Answers5

9

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 [].

Adam Zalcman
  • 26,643
  • 4
  • 71
  • 92
4

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.

pjumble
  • 16,880
  • 6
  • 43
  • 51
2

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.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368
2

try this: if (!preg_match('/^([0-9]{4})\-([0-9]{2})/', $expirationDate, $matches)) {

Leonardo
  • 3,141
  • 3
  • 31
  • 60
2

Try this it will help check both date format and check if the date if valid or not:

if (!preg_match('/^([0-9]{4})\-([0-9]{2})$/', $expirationDate, $matches)) {
    throw new Services_Payment_Exception('Card expiration date is wrong format');

}else if ( !strtotime($expirationDate) ){
    throw new Services_Payment_Exception('Card expiration date is invalid');
}
Thavarith
  • 287
  • 1
  • 3
  • 13