Paramclasses Academy - Blog

Tutorials Details

←
Post 18 of 40
→

How to Validate Forms and Handle User Input in Android Java ?

How to Validate Forms and Handle User Input in Android Java ?

November 3, 2026

1. Introduction

Forms are an important part of Android applications. Registration screens, login pages, contact forms and profile screens all collect information from users.

But what happens when a user submits an empty name, an invalid email address or a password that is too short?

This is where Form Validation becomes important.

In this tutorial, we will learn how to:

  • Get input from EditText fields.

  • Check whether required fields are empty.

  • Validate email addresses.

  • Validate phone numbers.

  • Check password length.

  • Confirm that two passwords match.

  • Display errors using setError().

  • Submit a form only when all fields are valid.

By the end, we will build a practical Registration Form using Java and XML in Android Studio.

2. What Is Form Validation?

Form validation is the process of checking user input before accepting or processing it.

For example, a registration form may require:

  • Full Name: Cannot be empty.

  • Email: Must have a valid email format.

  • Phone Number: Must contain 10 digits for this example.

  • Password: Must contain at least 8 characters.

  • Confirm Password: Must match the original password.

If the user enters incorrect information, the app should display a helpful error message.

Important: Android-side validation improves the user experience, but it does not replace server-side validation. A backend must validate submitted information again.

3. Understanding EditText Input

In Android, EditText is used to collect text from users.

First, connect an EditText from XML to Java using findViewById().

EditText etName;

etName = findViewById(R.id.etName);

To get the value entered by the user:

String name = etName.getText().toString();

To remove unnecessary spaces from the beginning and end:

String name = etName.getText().toString().trim();

The trim() method is useful for fields such as names and email addresses.

For passwords, avoid trimming automatically unless your application explicitly defines that behavior.

4. Displaying Validation Errors with setError()

Android provides the setError() method to show an error message beside an EditText field.

etName.setError("Name is required");

If the input becomes valid, you can clear the error:

etName.setError(null);

For example:

if (name.isEmpty()) {
    etName.setError("Please enter your name");
    etName.requestFocus();
}

Here:

  • isEmpty() checks whether the string contains no characters.

  • setError() displays the error message.

  • requestFocus() moves the user's focus to the incorrect field.

5. Understanding Different Validation Methods

5.1 Required Field Validation

Use isEmpty() to check whether a required field is empty.

if (name.isEmpty()) {
    etName.setError("Name is required");
    return false;
}

5.2 Email Validation

Android provides Patterns.EMAIL_ADDRESS to check email formatting.

if (!android.util.Patterns.EMAIL_ADDRESS
        .matcher(email).matches()) {

    etEmail.setError("Enter a valid email address");
    return false;
}

This is better than creating a complicated email regular expression for a beginner project.

5.3 Phone Number Validation

For this tutorial, we will require exactly 10 digits.

if (!phone.matches("[0-9]{10}")) {
    etPhone.setError("Enter a valid 10-digit phone number");
    return false;
}

This is a simple example for a 10-digit phone-number format. Real applications should account for their supported countries and phone-number formats.

5.4 Password Length Validation

We will require at least 8 characters.

if (password.length() < 8) {
    etPassword.setError("Password must be at least 8 characters");
    return false;
}

5.5 Confirm Password Validation

The confirm password field must match the original password.

if (!password.equals(confirmPassword)) {
    etConfirmPassword.setError("Passwords do not match");
    return false;
}

6. Practical Project: Create a Registration Form

Now let's build a working registration form.

Step 1: Create an Android Studio Project

  1. Open Android Studio.

  2. Create a new project.

  3. Select an Empty Views Activity template.

  4. Set the project name to FormValidationApp.

  5. Select Java as the programming language.

  6. Finish creating the project.

Step 2: Design the XML Layout

Open:

app > res > layout > activity_main.xml

Replace its content with the following XML:

<?xml version="1.0" encoding="utf-8"?>

<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="20dp">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Registration Form"
            android:textSize="24sp"
            android:textStyle="bold"
            android:gravity="center"
            android:padding="12dp" />

        <EditText
            android:id="@+id/etName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Full Name"
            android:inputType="textPersonName" />

        <EditText
            android:id="@+id/etEmail"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Email Address"
            android:inputType="textEmailAddress" />

        <EditText
            android:id="@+id/etPhone"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Phone Number"
            android:inputType="phone"
            android:maxLength="10" />

        <EditText
            android:id="@+id/etPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Password"
            android:inputType="textPassword" />

        <EditText
            android:id="@+id/etConfirmPassword"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="Confirm Password"
            android:inputType="textPassword" />

        <Button
            android:id="@+id/btnRegister"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Register"
            android:layout_marginTop="20dp" />

    </LinearLayout>

</ScrollView>

Understanding the XML:

  • ScrollView allows the form to scroll when the keyboard or a smaller screen reduces the available space.

  • LinearLayout arranges the form fields vertically.

  • EditText collects information from the user.

  • inputType provides an appropriate keyboard for each field.

  • maxLength="10" limits the phone field to 10 entered characters.

  • Button allows the user to submit the form.

Step 3: Write Java Code

Open:

app > java > your package name > MainActivity.java

Add the following code:

package com.example.formvalidationapp;

import android.os.Bundle;
import android.util.Patterns;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    EditText etName, etEmail, etPhone;
    EditText etPassword, etConfirmPassword;
    Button btnRegister;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Connect XML views with Java
        etName = findViewById(R.id.etName);
        etEmail = findViewById(R.id.etEmail);
        etPhone = findViewById(R.id.etPhone);
        etPassword = findViewById(R.id.etPassword);
        etConfirmPassword = findViewById(R.id.etConfirmPassword);

        btnRegister = findViewById(R.id.btnRegister);

        // Register button click event
        btnRegister.setOnClickListener(v -> {

            if (validateForm()) {

                Toast.makeText(
                        MainActivity.this,
                        "Registration Successful",
                        Toast.LENGTH_LONG
                ).show();

            }

        });
    }

    private boolean validateForm() {

        // Get user input
        String name = etName.getText().toString().trim();
        String email = etEmail.getText().toString().trim();
        String phone = etPhone.getText().toString().trim();

        String password = etPassword.getText().toString();
        String confirmPassword =
                etConfirmPassword.getText().toString();

        // Validate name
        if (name.isEmpty()) {
            etName.setError("Name is required");
            etName.requestFocus();
            return false;
        }

        // Validate email
        if (email.isEmpty()) {
            etEmail.setError("Email is required");
            etEmail.requestFocus();
            return false;

        } else if (!Patterns.EMAIL_ADDRESS
                .matcher(email).matches()) {

            etEmail.setError("Enter a valid email address");
            etEmail.requestFocus();
            return false;
        }

        // Validate phone number
        if (!phone.matches("[0-9]{10}")) {
            etPhone.setError("Enter a valid 10-digit phone number");
            etPhone.requestFocus();
            return false;
        }

        // Validate password
        if (password.isEmpty()) {
            etPassword.setError("Password is required");
            etPassword.requestFocus();
            return false;

        } else if (password.length() < 8) {

            etPassword.setError(
                    "Password must be at least 8 characters"
            );

            etPassword.requestFocus();
            return false;
        }

        // Confirm password
        if (confirmPassword.isEmpty()) {
            etConfirmPassword.setError(
                    "Please confirm your password"
            );

            etConfirmPassword.requestFocus();
            return false;

        } else if (!password.equals(confirmPassword)) {

            etConfirmPassword.setError(
                    "Passwords do not match"
            );

            etConfirmPassword.requestFocus();
            return false;
        }

        // All validations passed
        return true;
    }
}

Important: Replace the package declaration at the top with your own app's actual package name. Do not copy com.example.formvalidationapp if your project uses a different package.

Step 4: Understand the Java Code

Let's understand the important parts.

1. Connecting XML Views

etName = findViewById(R.id.etName);

This connects the XML EditText with the Java variable.

2. Getting User Input

String name = etName.getText().toString().trim();

This retrieves the text entered by the user and removes extra spaces from the beginning and end.

3. Button Click Event

btnRegister.setOnClickListener(v -> {
    if (validateForm()) {
        // Registration successful
    }
});

When the user clicks Register, the validateForm() method runs.

4. Returning false

return false;

This means validation failed. The registration-success code will not execute.

5. Returning true

return true;

This means all validation checks passed.

6. Showing a Toast

Toast.makeText(
    MainActivity.this,
    "Registration Successful",
    Toast.LENGTH_LONG
).show();

This displays a short success message.

Remember: this example only validates the form. It does not create an account or save registration data to a database.

7. Run and Test the Application

Run the application on an emulator or Android phone.

Test these cases:

Test 1: Empty Form

  • Leave every field empty.

  • Click Register.

  • The name field should show an error.

Test 2: Invalid Email

  • Enter a name.

  • Enter an invalid email, such as abc123.

  • Click Register.

  • The email field should show an error.

Test 3: Invalid Phone Number

  • Enter fewer than 10 digits.

  • Click Register.

  • The phone field should show an error.

Test 4: Short Password

  • Enter a password containing fewer than 8 characters.

  • Click Register.

  • The password field should show an error.

Test 5: Password Mismatch

  • Enter two different passwords.

  • Click Register.

  • The confirm password field should show an error.

Test 6: Valid Registration Form

  • Enter a name.

  • Enter a valid email.

  • Enter a 10-digit phone number.

  • Enter a password of at least 8 characters.

  • Enter the same password in Confirm Password.

  • Click Register.

You should see:

Registration Successful

8. Common Mistakes to Avoid

Mistake 1: Forgetting toString()

Incorrect:

String name = etName.getText();

Correct:

String name = etName.getText().toString();

Mistake 2: Not Using trim() for Name and Email

Extra spaces can cause unexpected validation problems. Use trim() for fields where surrounding spaces should be ignored.

Mistake 3: Comparing Strings with ==

Incorrect:

if (password == confirmPassword) {
}

Correct:

if (password.equals(confirmPassword)) {
}

Mistake 4: Showing Success Before Validation

Always validate the form first. Show a success message only when validateForm() returns true.

Mistake 5: Trusting Only Android Validation

Never rely only on client-side validation. Validate the submitted data again on your backend.

Mistake 6: Storing Passwords as Plain Text

Never store user passwords as plain text. Use a secure authentication system or properly designed server-side password hashing.

9. Practice Tasks

Try these tasks yourself:

  1. Add a Username field and make it required.

  2. Add a minimum 3-character condition for the name.

  3. Add a checkbox for accepting Terms and Conditions.

  4. Prevent registration if the checkbox is not selected.

  5. Clear all form fields after successful submission.

  6. Display a separate error message for every invalid field.

Try completing these tasks without copying the code immediately. This will improve your practical understanding of Java and Android event handling.

10. Conclusion

In this tutorial, we learned how to handle user input and validate a registration form in Android Studio using Java.

We covered:

  • EditText input handling.

  • Required field validation.

  • Email validation using Patterns.EMAIL_ADDRESS.

  • Phone number validation.

  • Password length and confirmation checks.

  • Error messages using setError().

  • Form submission using a Button click listener.

Form validation is an essential skill for building reliable Android applications. You will use these concepts in login screens, registration pages, profile forms and many other real-world projects.

11. Frequently Asked Questions (FAQs)

Q1. What is form validation in Android?

Form validation checks whether the information entered by a user meets the application's requirements before processing it.

Q2. How do we get text from EditText in Java?

Use getText().toString() to retrieve the entered text.

Q3. What is the use of setError() in Android?

The setError() method displays an error message on an EditText field when the entered information is invalid.

Q4. How can we validate an email address in Android Java?

Use Patterns.EMAIL_ADDRESS.matcher(email).matches().

Q5. How do we compare two passwords?

Use the equals() method:

password.equals(confirmPassword)

Q6. Why should we use requestFocus()?

It moves the input focus to the field that needs correction, helping the user identify the problem.

Q7. Is Android-side validation enough for a real application?

No. The backend must also validate submitted information because client-side checks can be bypassed.

←
Post 18 of 40
→