This example show how to prevent null and blank field. Here username field check whether the submitted value is null or some blank space. If the submitted value is null or blank it displays a error message. Another amount field prevent user from entering negative value in the field, it simply uses android:inputType="numberDecimal" to prevent user to enter negative value. Likewise you can limit input size with android:maxLength="20", this limits text size to 20 characters.
Click Here to download Source Code
Fig: Form Validation |
FormValidationExampleActivity.java
package com.rnd.action;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class FormValidationExampleActivity extends Activity{
/** Called when the activity is first created. */
EditText username, amount;
Button btn;
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
username = (EditText) findViewById(R.id.username);
amount = (EditText) findViewById(R.id.amount);
btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.d("Checking value of textbox", amount.getText().toString());
if(formValidator(username.getText().toString()) == true)
{
Toast.makeText(FormValidationExampleActivity.this, "Valid Data", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(FormValidationExampleActivity.this, "Name field is required", Toast.LENGTH_LONG).show();
}
}
});
}
public boolean formValidator(String values)
{
if((values.trim()).equals("") || values.equals(null))
{
return false;
}
else
{
return true;
}
}
public void checkemail(String email)
{
Pattern pattern = Pattern.compile(".+@.+\\.[gmail.com]+");
Matcher matcher = pattern.matcher(email);
boolean emailcheck = matcher.matches();
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
>
<requestFocus />
</EditText>
<EditText
android:id="@+id/amount"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Ok" />
</LinearLayout>