I am using this regex pattern to allow only valid characters. "^[a-z_A-Z0-9 ]*$";
This expression allows only characters from a-z,
A-Z and numbers from 0-9 and a ‘ ‘(space) character.
Here is the java code
package com.valid;
import
java.util.regex.Matcher;
import
java.util.regex.Pattern;
import
android.app.Activity;
import android.os.Bundle;
import
android.view.View;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.EditText;
import
android.widget.Toast;
public class
ValidationActivity extends Activity {
EditText tbox;
Button but;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tbox = (EditText)findViewById(R.id.EditText01);
but
= (Button)findViewById(R.id.Button01);
but.setOnClickListener(new
OnClickListener() {
public void onClick(View v)
{
if(isValid(tbox.getText().toString().trim())){
Toast.makeText(getApplicationContext(),
"Text
entered is OK.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(),
"Oops!!
Text entered is Invalid.", Toast.LENGTH_SHORT).show();
}
}
});
}
public static boolean isValid(String str)
{
boolean isValid = false;
String expression = "^[a-z_A-Z0-9
]*$";
/**This interface represents an
ordered set of characters and defines the methods to probe them.**/
CharSequence inputStr = str;
Pattern pattern = Pattern.compile(expression);
Matcher matcher =
pattern.matcher(inputStr);
if(matcher.matches())
{
isValid = true;
}
return isValid;
}
}
main.xml
<?xml version="1.0"
encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText
android:text=""
android:hint="enter some text"
android:id="@+id/EditText01"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</EditText>
<Button
android:text="Test"
android:id="@+id/Button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
Snapshot:- 

|