Pages

March 4, 2010

Android EditText Validation Example [updated]

Validation on user input can be applied by regular expressions. It provides a concise and flexible means for matching strings of text, such as particular characters, words, or patterns of characters.

There are two ways to validate/restrict user input:
  1. Validate user entered data.
  2. Restrict user input to certain things like DIGITs only, CHARACTERs only etc.
 #1.Validate user entered data

 in  this case validation isapplied  generally on #onClickEvent of button
 here in this example we are checking if String is DIGIT only

String invalidStr="AB10",validStr="0998257476";

Pattern pattern=Pattern.compile("[0-9]*");

//argument to matcher is string to validate
Matcher matcher=pattern.matcher(invalidStr);        

if(!matcher.matches())       // on Success 
{ 
    //invalid
    //pop up ERROR  message
    Toast.makeText(context," Invalid Input ",Toast.LENGTH_LONG).show();

}else
{ 
    //validation succesfull
    //Go Ahead !!  
}

If we validate : invalidStr output would be INVALID and for validStr , it is  VALID change RE as per your validation needs..

#2 Restrict user input to certain types:

<Edittext android:inputType="number"
   android:layout_height="wrap_content"
   android:layout_width="fill_parent">
</>
 
Other inputType can be email address,password,phone number etc. refer documentation.    
RE online testing tool : www.fileformat.info/tool/regex.htm  
RE Library Regexlib.com
Refrence Links to RE

Cheers :)
If you have any query drop it in comments..

No comments:

Post a Comment