Anda di halaman 1dari 15

Validation in Android

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

2. When the end user changes text in a text field

3. When a text field loses focus

4. When a form is submitted

Scenario 1: Before the User Enters Any Text

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:

Android Layout XML file

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>

Android Layout XML file.


package com.javatechig;

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;

public class MainActivity extends Activity {

private EditText emailEditText;

private EditText passEditText;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

emailEditText = (EditText) findViewById(R.id.editText_email);

passEditText = (EditText) findViewById(R.id.editText_password);

findViewById(R.id.btn_signup).setOnClickListener(new
OnClickListener() {

@Override

public void onClick(View arg0) {

final String email = emailEditText.getText().toString();

if (!isValidEmail(email)) {

emailEditText.setError("Invalid Email");

final String pass =


passEditText.getText().toString();

if (!isValidPassword(pass)) {

passEditText.setError("Invalid Password");

}
}

});

// validating email id

private boolean isValidEmail(String email) {

String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"

+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})
$";

Pattern pattern = Pattern.compile(EMAIL_PATTERN);

Matcher matcher = pattern.matcher(email);

return matcher.matches();

// validating password with retype password

private boolean isValidPassword(String pass) {

if (pass != null && pass.length() > 6) {

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;

public class MainActivity extends Activity {

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);

Button b1 = (Button) findViewById(R.id.button1);


b1.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub

//Validation for Blank Field


if(et1.getText().toString().length()==0)
{
Toast.makeText(getApplicationContext(),
"Name cannot be Blank", Toast.LENGTH_LONG).show();
et1.setError("Name cannot be Blank");
return;
}
else if(!
android.util.Patterns.EMAIL_ADDRESS.matcher(et2.getText().toString()).ma
tches())
{
//Validation for Invalid Email Address
Toast.makeText(getApplicationContext(),
"Invalid Email", Toast.LENGTH_LONG).show();
et2.setError("Invalid Email");
return;
}
else if(!
android.util.Patterns.DOMAIN_NAME.matcher(et3.getText().toString()).mat
ches())
{
//Validation for Website Address
Toast.makeText(getApplicationContext(),
"Invalid Website", Toast.LENGTH_LONG).show();
et3.setError("Invalid Website");
return;
}
else
{
Toast.makeText(getApplicationContext(),
"Validated Succesfully", Toast.LENGTH_LONG).show();
}

}
});
}

@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).

To do this you have to implement a TextChangedListener which must implement


the TextWatcher interface. The annoyance here is that you have to do this on a field by
field basis so you need a way to homogenize the implementation or you will have
tons of repetitive code this is done by creating an abstract class
called TextValidator which implements the TextWatcher interface

The key method in this class is afterTextChanged. My flavor of it is shown below (I


dont pass the text separately to the validate method).

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.

Scenario 3: When a Text Field Loses Focus


The setup for validation when a text field loses focus is very similar to the one described
above. There are just two small additions:

The line in green above adds the on focus change listener which works the same
way as the text change listener.

The ContactValidator class has an OnFocusChange method which calls the


validate method and it implements the OnFocusChangeListener interface.
Scenario 4: When a Form is Submitted

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.

Anda mungkin juga menyukai