Validating Form Input

Now let’s add validation to ensure users enter valid payment information. We will check the expiration date, CVV, and set up card number validation.

Validating the Expiration Date

Let’s add validation to check if the card has expired. Update handleFormSubmit to include the date check.

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

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

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

We create a Date object from the entered year and month, then compare it against today’s date. If the card is expired, we show an alert and return early so the rest of the function does not run.

Notice we use month - 1 because JavaScript’s Date constructor uses 0-indexed months (January is 0, December is 11). When a user enters 12 for December, we need to pass 11 to Date.

Validating the CVV with Regular Expressions

A valid CVV is a 3 or 4 digit number. Update handleFormSubmit to add CVV validation.

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

  const month = document.getElementById("month").value;
  const year = document.getElementById("year").value;
  if (new Date() > new Date(year, month - 1)) {
    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 what each part of the pattern /^[0-9]{3,4}$/ means:

Part Meaning
^ Start of string
[0-9] Any digit (0 through 9)
{3,4} Between 3 and 4 times
$ End of string

Setting Up Card Number Validation

To validate the card number, we will delegate the logic to a separate function.

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

  const month = document.getElementById("month").value;
  const year = document.getElementById("year").value;
  if (new Date() > new Date(year, month - 1)) {
    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;
  }

+ const cnumber = document.getElementById("cnumber").value;
+ if (!isValid(cnumber)) {
+   window.alert("Invalid card number!");
+   return;
+ }

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

+ function isValid(cnumber) {
+   return true;
+ }

For now, isValid always returns true. In the next section, we will implement the actual validation using the Luhn algorithm.

Checkpoint: Commit your progress.

git add .
git commit -m "payment-02: Add form validation for expiration date and CVV"
git push