What is validation?
Types of Validation?
Getting Started
The first question I had to answer was when did I want to validate fields? I came up
with four different scenarios:
1. Before the end user even enters data by setting them up for success
Android provides a long list of input types that you can set in the layout XML to set the
user up for success so that they can only enter permissible characters or numbers. For
example: an input type of phone leads to only numbers, and characters such as -, (, )
being available for the user to enter:
Let us create an layout xml file with two EditText field one for entering email-id
and other for password.
<LinearLayout 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:background="#F0F0F0"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="@string/lbl_register"
android:textAllCaps="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#176CEC"
android:textStyle="bold" />
<EditText
android:id="@+id/editText_email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#fff"
android:ems="10"
android:hint="@string/lbl_email_hint"
android:inputType="textEmailAddress"
android:padding="12dp" />
<EditText
android:id="@+id/editText_password"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="1dp"
android:background="#fff"
android:ems="10"
android:hint="@string/lbl_password_hint"
android:inputType="textPassword"
android:padding="12dp" />
<Button
android:id="@+id/btn_signup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#176CEC"
android:text="@string/lbl_btn_signup"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#fff"
android:textStyle="bold" />
</LinearLayout>
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.EditText;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_signup).setOnClickListener(new
OnClickListener() {
@Override
if (!isValidEmail(email)) {
emailEditText.setError("Invalid Email");
if (!isValidPassword(pass)) {
passEditText.setError("Invalid Password");
}
}
});
// validating email id
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})
$";
return matcher.matches();
return true;
return false;
}
}
Output
Validation Example 2
Activity_main.xml
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="android.edittext.validation.MainActivity" >
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="26dp"
android:hint="Name"
android:ems="10" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="29dp"
android:ems="10"
android:hint="Email"
android:inputType="textEmailAddress" />
<EditText
android:id="@+id/editText3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText2"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
android:hint="Website"
android:ems="10" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText3"
android:layout_centerHorizontal="true"
android:layout_marginTop="27dp"
android:text="Submit" />
</RelativeLayout>
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
EditText et1,et2,et3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Name
et1 = (EditText) findViewById(R.id.editText1);
//Email
et2 = (EditText) findViewById(R.id.editText2);
//Website
et3 = (EditText) findViewById(R.id.editText3);
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Scenario 2: When the End User Changes Text in a Text Field
Next up: what you can do when the user changes the text in a field and still manages to
enter something incorrect, even though we set them up for success above. Well, if it can
be done unobtrusively, the next best time to validate is when the user is actually entering
the text (this is also where we can implement the cool icon and error message shown in
the first screen).
Then I created a concrete class that extends the TextValidator class and implements the
validate method:
I highlighted in red the two key elements of this class, that it extends TextValidator, and
how to get the cool icon and error message. Using TextView.setError gives us the
desired visual validation.
Now, the last step is to set this validator onto the text fields of interest. Since I wanted it
set in all the text fields in my Activity, I created a factory class to set up the validation
on all the text fields:
The 3 lines of code highlighted in blue are used to retrieve a list of all the elements on
the screen. The code then loops through all of them looking for text boxes (EditText).
For each EditText it finds, the line highlighted in red adds the on text change listener to
the text box. The listener is used to trigger the validation logic whenever the user
changes the text in the field.
The line in green above adds the on focus change listener which works the same
way as the text change listener.
The final step in the validation is to make sure that the form is only submitted for further
processing if there are no validation errors. Since the Activity keeps track of the state of
all of its component elements, this becomes an easy task. You just need to check if an
error message is set for any of the elements or not. If it is, then the form is not valid:
Im this method the ContactValidatorFactory class and then called it from the submit
method tied to the submit button on the form.