簡體   English   中英

驗證輸入-字符串

[英]Validate Input - String

我試圖驗證來自文本字段的輸入,以便它僅包含來自z的字符。 我正在使用以下方法來驗證輸入是否為int:

//VALIDATE IF INPUT IS NUMERIC.
public static boolean isInt(JFXTextField txtUserInput, String userInput) {
    try {
        int intValidation = Integer.parseInt(userInput);
        txtUserInput.setStyle("-fx-border-color: ; -fx-border-width: 0px ;");
        return true;
    } catch(NumberFormatException exception) {
        showErrorMsg("Invalid Input:", "Please enter a numeric-only value");
        txtUserInput.setStyle("-fx-border-color: RED; -fx-border-width: 1px ;");
        return false;
    }
}

如何使用字符串實現此目的? 我知道有一種使用if語句執行此操作的方法,但是我想知道是否可以像上面的示例一樣捕獲異常。

謝謝

您可以將matches與正則表達式配合使用,因此,如果要檢查輸入的內容是否為整數,可以使用:

String userInput = ...;
if(userInput.matches("\\d+")){
    System.out.println("correct");
}else{
    System.out.println("Not correct");
}

如果要檢查輸入是否僅包含字母,可以使用:

if(userInput.matches("[a-zA-Z]+")){
    System.out.println("correct");
}else{
    System.out.println("Not correct");
}

如果要檢查您的輸入是否包含字母數字,可以使用:

if(userInput.matches("[a-zA-Z0-9]+")){
    System.out.println("correct");
}else{
    System.out.println("Not correct");
} 

使用正則表達式:

if (!userInput.matches("[a-z]+"))
    // Has characters other than a-z

如果也要允許大寫:

if (!userInput.matches("[a-zA-Z]+"))
    // Has characters other than a-z or A-Z

您可以使用類似:

if (!userInput.matches(".*[^a-z].*")) { 
    // Do something
}

@ Bohemian♦的替代解決方案,允許大寫:

if (!userInput.toLowerCase().matches(".*[^a-z].*")) { 
    // Do something
}

根據您的來源,類似的方法:

public static boolean containsAZ(JFXTextField txtUserInput) {
        if (!txtUserInput.getText().toLowerCase().matches(".*[^a-z].*"))
            return true;
        else
            System.err.println("Input is not containing chars between A-Z");

        return false;
}

您的問題是,如果有可能引發/捕獲異常,則可以執行以下操作:

public static boolean containsAZ(JFXTextField txtUserInput) {
        try {
            if (!txtUserInput.toLowerCase().matches(".*[^a-z].*")) {
                return true;
            } else
                throw new MyException("Something happened");
        } catch (MyException e) {
            e.printStackTrace();
        }
        return false;
    }

考慮到您需要一個課程:

class MyException extends Exception {

    public MyException(String e) {
        System.out.println(e);
    }

}

一個抽象的解決方案是:

public class MyException extends Exception {
        // special exception code goes here
}

拋出為:

 throw new MyException ("Something happened")

捕捉為:

catch (MyException e)
{
   // Do something
}

有關更多信息, 請檢查regex

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM