YearMonth Expiry Validation

Validate card expiry printed as MM/yy with YearMonth.parse: the printed month stays valid through its last day, so only earlier months count as expired.

JavaForm Validation

Code

snippet
import java.time.YearMonth;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

public class CardExpiryValidator {

    private static final DateTimeFormatter MM_YY = DateTimeFormatter.ofPattern("MM/yy");

    static boolean isExpired(String printed, YearMonth today) {
        try {
            YearMonth expiry = YearMonth.parse(printed, MM_YY);
            // 有效期覆盖整月:到期月最后一天前都可用
            return expiry.isBefore(today);
        } catch (DateTimeParseException e) {
            throw new IllegalArgumentException("bad expiry: " + printed, e);
        }
    }

    public static void main(String[] args) {
        YearMonth today = YearMonth.of(2026, 11);
        for (String card : new String[] {"11/26", "12/26", "10/26"}) {
            System.out.println(card + " -> " + (isExpired(card, today) ? "expired" : "valid"));
        }
    }
}

How the snippet works

The code’s whole job belongs to the class CardExpiryValidator and the functions isExpired and main.

Repetition is confined to for (String card : new String[] {"11/26", "12/26", "10/26"}) — the rest of the file is straight-line. IllegalArgumentException is the guard’s signal — thrown at the branch, before any partial work happens.

Applying it

Entry signature: static boolean isExpired(String printed, YearMonth today)

Execute the file and main walks through isExpired, in that order.

Statements that matter

throw new IllegalArgumentException("bad expiry: " + printed, e);
return expiry.isBefore(today);

Interactive Tools for This Topic

FAQ

What does the snippet do with malformed data?
It throws `IllegalArgumentException` before any real work runs — handle it at the call site or let it propagate deliberately.
How do you run YearMonth Expiry Validation?
Just run the file; everything it needs ships with the runtime itself.