Step 6

Let's examine the card validation value, CVV. For this demo, it is sufficient to check that CVV is a 3 or 4 digit numeric value.

const cvv = document.getElementById("cvv").value;
if (!/^[0-9]{3,4}$/.test(cvv)) {
  window.alert("Invalid CVV. It must be 3 or 4 digits!");
  return;
}

Add the above snippet to handleFormSubmit as shown below:

function handleFormSubmit(event) {
  event.preventDefault();

  const month = document.getElementById("month").value;
  const year = document.getElementById("year").value;
  if (new Date() > new Date(year, month)) {
    window.alert("Your card is expired!");
    return;
  }

+ const cvv = document.getElementById("cvv").value;
+ if (!/^[0-9]{3,4}$/.test(cvv)) {
+   window.alert("Invalid CVV. It must be 3 or 4 digits!");
+   return;
+ }

  window.alert("Thanks for the payment!");
}

Here is the payment form in action:

To match 3 or 4 digits, I used the following regular expression pattern:

/^[0-9]{3,4}$/

Explanation:

  • ^: Start of string anchor
  • [0-9]: Digit between 0 and 9 (you could also use \d here)
  • {3,4}: A quantifier meaning between 3 and 4 (inclusive).
  • $: End of string anchor

Regular expressions are patterns used to match character combinations in strings.

Regular expressions are powerful! However, it is beyond the scope of this course to explore them. Instead, please refer to the resources below for more information.

Resources