Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 953
topacoBoy Avatar asked Mar 13 '16 14:03

topacoBoy


1 Answers

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
like image 184
Mattias Isegran Bergander Avatar answered Nov 17 '22 13:11

Mattias Isegran Bergander