Technical

How to Build Client-Side Payment Form Validation in JavaScript

November 5, 2025 · 5 min read · By Yasir Khan

← Back to Blog

A payment form is the last thing a customer sees before they hand over money, and small friction here costs real sales. Client-side validation helps by catching typing mistakes the moment they happen, while the customer can still fix them easily. This guide walks through the techniques that matter: preparing the input, checking the number, validating the expiry date, writing clear and accessible errors, and keeping sensitive data safe.

What client-side validation is for

Validation in the browser improves the experience. It does not provide security. Anyone can bypass browser code, so everything must be checked again on the server, and the real decision about a card always belongs to the payment provider. Think of your JavaScript as a helpful assistant that says “that number looks one digit short”, not as a gatekeeper.

A privacy bonus comes with this approach: a check that runs in the browser never sends the number anywhere. That is how the card checks on our own validator work.

Start with good markup

Much of a good payment form is plain HTML. Use the right attributes and the browser will do part of the work for you, including autofill, which is the fastest and least error-prone input method of all:

<label for="cc-number">Card number</label>
<input id="cc-number" name="cardnumber" type="text"
       inputmode="numeric" autocomplete="cc-number"
       spellcheck="false" aria-describedby="cc-number-error">
<p id="cc-number-error" role="alert"></p>

<label for="cc-exp">Expiry (MM/YY)</label>
<input id="cc-exp" name="exp" type="text"
       inputmode="numeric" autocomplete="cc-exp">

A few points are worth noting. Use type="text" with inputmode="numeric" rather than type="number", because number inputs can strip leading zeros and show spinner arrows. The autocomplete tokens such as cc-number and cc-exp let browsers fill in saved cards, and you can read the full list in the MDN autocomplete reference.

Normalize before you validate

People type card numbers with spaces, hyphens or even dots, and paste them in from many sources. Strip those out before running any check, and always keep the value as a string:

const digitsOnly = (value) => String(value).replace(/\D/g, "");

function formatCardNumber(value) {
  return digitsOnly(value).slice(0, 19).replace(/(.{4})/g, "$1 ").trim();
}

Formatting in groups of four as the customer types makes the number easier to proofread. Do not move the cursor unexpectedly, and test pasting and deleting in the middle of the field, which is where naive formatters misbehave.

Check the number

Two quick checks cover most mistakes: the length and the Luhn checksum. Different networks allow different lengths, as described in our guide to international card schemes, so allow 12 to 19 digits and let the checksum do the real work:

function validateCardNumber(raw) {
  const digits = digitsOnly(raw);
  if (digits.length < 12 || digits.length > 19) {
    return "Card numbers have 12 to 19 digits.";
  }
  let sum = 0, double = false;
  for (let i = digits.length - 1; i >= 0; i--) {
    let d = Number(digits[i]);
    if (double) { d *= 2; if (d > 9) d -= 9; }
    sum += d;
    double = !double;
  }
  return sum % 10 === 0 ? "" : "Please check the number: a digit may be wrong.";
}

Because some networks, such as UnionPay, do not always satisfy the Luhn rule, consider showing a gentle warning instead of blocking the customer in those cases.

Check the expiry date

A card is valid through the end of the month printed on it, which is an easy detail to get wrong:

function validateExpiry(raw) {
  const m = String(raw).trim().match(/^(0[1-9]|1[0-2])\s*\/?\s*(\d{2})$/);
  if (!m) return "Use the format MM/YY.";

  const month = Number(m[1]);
  const year = 2000 + Number(m[2]);
  const endOfMonth = new Date(year, month, 0, 23, 59, 59);

  return endOfMonth < new Date() ? "This card has expired." : "";
}

Passing month as the day-zero of the following month gives the last day of the expiry month. Do not accept dates implausibly far in the future, since a typo such as 12/92 is more likely than a card valid for sixty-six years.

The security code

The card security code is three digits on most cards and four on American Express. Validate only its length and digit-only format, and never store it. Merchants are not permitted to keep it after authorization, so the safest design is one in which it never touches your own servers at all.

Accessible, kind error messages

  • Validate on blur, not on every keystroke. Showing an error while someone is halfway through typing is frustrating.
  • Be specific. “The expiry date should look like 08/27” helps more than “Invalid input”.
  • Connect messages to fields. Use aria-describedby and set aria-invalid="true" so screen readers announce the problem.
  • Do not rely on colour alone. Pair red text with an icon or a clear sentence.
  • Keep the keyboard flow. Move focus to the first invalid field when the form is submitted.

Keep sensitive data safe

Whatever you build, treat card details as hazardous material. Do not write them to the console, to analytics events or to error-tracking tools, and avoid storing them in localStorage or in the URL. For most businesses the best design is to use the payment provider’s hosted fields or payment page so that card data goes directly to the provider. We explain why in our guide to PCI DSS basics for developers.

Key takeaways

  • Client-side validation is a usability tool: it saves customers from typos, and the server and payment provider must still verify everything.
  • Use proper input attributes, normalize input to digits, and keep values as strings.
  • Check length, the Luhn checksum and the expiry date, remembering that a card is valid until the end of its expiry month.
  • Write specific, accessible messages, and keep card data out of logs and storage.

Visit the FAQ to see what a “valid” result does and does not mean.

Put it into practice: check the format of a card, routing or account number with the Tvalidora validator, look up an area code or zip code with the US Checker, or read the FAQ to see exactly what a “valid” result means. Tvalidora checks number format only, and never stores what you enter.

Keep reading