Home Next Tutorial

How To implement required field validation for edittext in Android


Step 1: Open Android Studio
Step 2: Select File->New->New Project
Step 3: In the Create New Project window type Application Name as "Validation" and click on Next button. In the Target Android Devices select Minimum SDK and click on Next Button. In The Add an Activity to Mobile select blank activity and click on Next Button.Click on Finish button.
Step 4: Design an activity as shown below:

Intent Example
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Name:"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:textColor="#010101" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/etName"
android:layout_below="@+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Display"
android:id="@+id/btnClick"

android:layout_below="@+id/etName"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="42dp" />
</RelativeLayout>

Step 5: Open MainActivity.java file and write following code in the onCreate() method to open second activity from MainActivity.

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button b1 = (Button)findViewById(R.id.btnClick);
final EditText et1 = (EditText)findViewById(R.id.etName);
b1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if(et1.getText().length()==0)
{
et1.setError("Please Enter Name");
}
else
{
Toast.makeText(getApplicationContext(),et1.getText().toString(),Toast.LENGTH_LONG).show();
}
}
});
}

Step 6:Run the application.


Download Projects


Download Programs