Hello,

I have a script that is taking credit card payment and I'm validating user input in a php script. Things are working fine until I try to validate the CVV number. For American Express (AMEX) it should be 4 numerical digits. For MasterCard or Visa (everything else) it should be 3 numerical digits.

When I use the following regular expression, it correctly throws an error if the AMEX CVV is less than 4 digits. But if it is not AMEX (e.g. it is mastercard or visa) I only get an error if the input is 1 or 2 digits. It should only validate for 3 digits, but 4 digits also validates.

Can somebody tell me why this doesn't work?

  trim($cvv);

  If ($paymentmethod == "AMEX") 
	{
	If (!ereg('([0-9]{4})', $cvv)) 
		{
		$errortext = "Please enter a valid CVV code";
		exit;
		}
	}
	// else mastercard or visa
	elseif (!ereg('([0-9]{3})', $cvv)) 
		{
		$errortext = "Please enter a valid CVV code";
		exit;
		}

    Well, for a start, [man]ereg[/man] has been deprecated for a couple of years now, so it'd be a good idea to upgrade your code.

    Your problem is that any CVV code that contains four digits also contains three digits, and therefore passes your "three-digit" test.

    You could fix this with ^ and $ anchors in your regular expression, or (and this is likely to be faster as well as simpler) just use [man]ctype_digit[/man] and [man]strlen[/man] to do the checks.

      What version of PHP are you using? ereg() has been deprecated as of 5.3.0 in favour of preg_match().

      Also your regular expressions aren't thorough. What you're currently testing is if what's entered contains 3 (or 4) consecutive numbers, but if I enter in 1234 for a Mastercard CVV, it would validate. Instead test of the whole string matches the pattern, rather than a portion of it.

      if(preg_match('/^[0-9]{4}$/', $cvv))//use {3} for non-AMEX cards
      {
      	//stuff if correct
      }
      else
      {
      	//stuff if incorrect
      }
      

      And Weedpacket beat me. 🙁

      EDIT: Doh! No post merging. Sorry. 🙁

      MOD EDIT: Sure there is! :p Posts merged.

        Write a Reply...