简体   繁体   中英

How to validate EditText input with a custom regex in Android?

I am new to android development and also regular expression. I am able to retrieve inputs from user through the EditText and check if it's empty and later display the error message if it is empty but I am not sure on how to check with a custom regex. Here's my code :

 myInput = (EditText) findViewById(R.id.myInput);
String myInput_Input_a = String.valueOf(myInput.getText());

//replace if input contains whiteSpace
String myInput_Input = myInput_Input_a.replace(" ","");


    if (myInput_Input.length()==0 || myInput_Input== null ){

               myInput.setError("Something is Missing! ");
     }else{//Input into databsae}

So, im expecting the user to input a 5 character long string where the first 2 letters must be numbers and the last 3 characters must be characters. So how can i implement it people ?

General pattern to check input against a regular expression:

String regexp = "\\d{2}\\D{3}"; //your regexp here

if (myInput_Input_a.matches(regexp)) {
    //It's valid
}

The above actual regular expression assumes you actually mean 2 numbers/digits (same thing) and 3 non-digits. Adjust accordingly.

Variations on the regexp:

"\\d{2}[a-zA-Z]{3}"; //makes sure the last three are constrained to a-z (allowing both upper and lower case)
"\\d{2}[a-z]{3}"; //makes sure the last three are constrained to a-z (allowing only lower case)
"\\d{2}[a-zåäöA-ZÅÄÖ]{3}"; //makes sure the last three are constrained to a-z and some other non US-ASCII characters (allowing both upper and lower case)
"\\d{2}\\p{IsAlphabetic}{3}" //last three can be any (unicode) alphabetic character not just in US-ASCII

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