简体   繁体   中英

How to validate that a string from a textbox contains only 2 characters and 3 numbers?

I have checked other answers and am not finding what I need to know. I have a variable named nationalID which can only contain 2 characters and 3 numbers (ex. aa123) How do I say this in java? I am using Netbeans and have looked at all of the methods that pops up but I am not seeing anything that will help me. This is what I have so far.

private String validator(String nationalID, String lastName, String firstName, String dateOfBirth) {
    // nationalID should have 2 characters and 3 digits ex. AB123
    // dateOfBirth should be yyyy-mm-dd

    if(nationalID.length() != 5 || nationalID.){
        String err;
        return err =  "Your National ID has to be 5 characters long";
    }

    return "";
}

Try using matches method of String with regex like:

 if(nationalID.matches("[A-Za-z]{2}[0-9]{3}")) {
     System.out.println("Yes it does contains pattern");
 }

[A-Za-z]{2} Means be it any two known character either between AZ or az.
[0-9]{3} Means be it any combination of numbers between 0-9 repeated thrice which follows two known characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM