kanna kanna - 1 month ago 19
Android Question

Validation allow only number and characters in edit text in android

In my application i have to validate the edittext. It should only allow character, digits, underscore and hypen.

Here is my code:

edittext.addTextChangedListener(new TextWatcher() {

public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub


public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub


public void afterTextChanged(Editable s) {
// validation codes here

Toast.makeText(getApplicationContext(),location_name, Toast.LENGTH_SHORT).show();

if (location_name.matches(".*[^a-z^0-9].*"))
location_name = location_name.replaceAll("[^a-z^0-9]", "");
Toast.makeText(getApplicationContext(),"Only lowercase letters and numbers are allowed!",Toast.LENGTH_SHORT).show();





in this , when i entered input in edittext ,application is force closed.please give me suggestion.Thanks in advance.


Instead of using your "manual" checking method, there is something very easy in android:

InputFilter filter = new InputFilter() { 
    public CharSequence filter(CharSequence source, int start, int end, 
Spanned dest, int dstart, int dend) { 
            for (int i = start; i < end; i++) { 
                    if ( !Character.isLetterOrDigit(source.charAt(i)) || !Character.toString(source.charAt(i)) .equals("_") || !Character.toString(source.charAt(i)) .equals("-")) { 
                            return ""; 
            return null; 

edit.setFilters(new InputFilter[]{filter}); 

Or another approach: Set the allowed characters in the xml where you are creating yor EditTExt:

  android:hint="Only letters, digits, _ and - allowed"