You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaFX信用卡页面中将文本框输入限制为仅数字?

Fixing Numeric Input Validation for JavaFX Credit Card Fields

Hey there! Let's sort out the issue where your JavaFX credit card input fields accept non-numeric text—right now you only catch empty fields, but invalid text slips through. Changing the variable type to Integer doesn't help because TextField inherently returns a String, and it doesn't restrict what users type by default. Here are two effective solutions:

1. Restrict Input in Real-Time (Prevent Non-Numeric Characters)

The cleanest way is to use a TextFormatter to filter out any non-digit characters as the user types. This way, they can't even enter invalid text in the first place.

Add this setup code for each of your fields (you can put this in your controller's initialize() method or when initializing the text fields):

// For card number field
cardtf.setTextFormatter(new TextFormatter<>(change -> {
    if (change.getControlNewText().matches("\\d*")) {
        return change;
    }
    return null;
}));

// For expiry month (expirytf1)
expirytf1.setTextFormatter(new TextFormatter<>(change -> {
    String newText = change.getControlNewText();
    // Limit to 2 digits for valid month range (01-12)
    if (newText.matches("\\d*") && newText.length() <= 2) {
        return change;
    }
    return null;
}));

// For expiry year (expirytf2)
expirytf2.setTextFormatter(new TextFormatter<>(change -> {
    String newText = change.getControlNewText();
    // Limit to 4 digits for full year (e.g., 2025)
    if (newText.matches("\\d*") && newText.length() <= 4) {
        return change;
    }
    return null;
}));

// For CVV field
cvvtf.setTextFormatter(new TextFormatter<>(change -> {
    String newText = change.getControlNewText();
    // CVV is typically 3-4 digits
    if (newText.matches("\\d*") && newText.length() <= 4) {
        return change;
    }
    return null;
}));

2. Validate Input on Submission (Catch Invalid Entries)

If you prefer to let users type anything but validate when they click the confirm button, update your thankyoupage method to check if each field contains only digits. You can use regex or try parsing the string to a number (with error handling):

Updated thankyoupage Method:

public void thankyoupage(ActionEvent actionEvent) throws IOException {
    String cardno = cardtf.getText();
    String expdate1 = expirytf1.getText();
    String expdate2 = expirytf2.getText();
    String cvvnum = cvvtf.getText();

    // Check for empty fields first
    if (cardno.isEmpty() || expdate1.isEmpty() || expdate2.isEmpty() || cvvnum.isEmpty()) {
        Alert alert = new Alert(Alert.AlertType.WARNING, "Enter Full Details", ButtonType.OK);
        alert.showAndWait();
        return;
    }

    // Check if all fields contain only numeric values
    if (!cardno.matches("\\d+") || !expdate1.matches("\\d+") || !expdate2.matches("\\d+") || !cvvnum.matches("\\d+")) {
        Alert alert = new Alert(Alert.AlertType.ERROR, "Please enter only numeric values for all fields", ButtonType.OK);
        alert.showAndWait();
        return;
    }

    // Optional: Add extra validation for realistic card rules
    if (cardno.length() < 13 || cardno.length() > 19) {
        Alert alert = new Alert(Alert.AlertType.ERROR, "Invalid credit card number length", ButtonType.OK);
        alert.showAndWait();
        return;
    }

    int expiryMonth = Integer.parseInt(expdate1);
    if (expiryMonth < 1 || expiryMonth > 12) {
        Alert alert = new Alert(Alert.AlertType.ERROR, "Invalid expiry month (must be 01-12)", ButtonType.OK);
        alert.showAndWait();
        return;
    }

    // If all checks pass, navigate to thank you page
    Window mainWindow = confirmbut.getScene().getWindow();
    Parent newRoot = FXMLLoader.load(getClass().getResource("Thankyou.fxml"));
    mainWindow.getScene().setRoot(newRoot);
}

Why Changing to Integer Didn't Work

When you tried switching the variable type to Integer, you probably tried parsing the TextField text directly without validation. This would throw a NumberFormatException if the input was non-numeric, but you weren't handling that exception. The above approach validates first before parsing, which avoids crashes and gives clear feedback to the user.

内容的提问来源于stack exchange,提问作者user11185206

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:32:21