User Registration Form Validation

Do While Loop in C#: User Registration Form Validation (Email Format Check)

Introduction

In user-centered software systems such as enrollment portals, e-commerce platforms, and enterprise information systems, input validation is a critical control mechanism. One common requirement in registration workflows is validating the user’s email address format before accepting the data. In this lesson, we will explore how to use a do while loop in C# to repeatedly prompt the user to enter an email address until it matches a valid format pattern.

Unlike a while loop, which checks the condition before executing the block of code, a do while loop executes the code block first and then evaluates the condition. This makes it ideal for input validation scenarios where the program must run at least once — such as asking the user to enter their email during registration.

By the end of this lesson, you will understand how to use a do while loop effectively in a practical validation scenario.


Lesson Objectives

This lesson is designed using Outcome-Based Education (OBE) principles to ensure measurable learning results. After completing this lesson, students are expected to demonstrate the following competencies:

Introductory Overview of Objectives

The objectives are structured to guide learners progressively — from conceptual understanding to practical implementation. Students will first comprehend how a do while loop operates, then learn how it integrates with validation logic, practice writing functional code, and finally apply the concept in real-world scenarios such as registration systems.

1. Understand

  • Explain the structure and syntax of a do while loop in C#.
  • Differentiate between while and do while loops.
  • Describe why do while is suitable for input validation.

2. Learn

  • Identify components of email format validation.
  • Use System.Text.RegularExpressions for pattern matching.
  • Implement conditional logic inside a loop.

3. Practice

  • Write a console-based program that validates user input.
  • Test different email formats to observe validation behavior.
  • Debug common logical errors.

4. Apply

  • Integrate email validation logic into a registration module.
  • Modify the code to validate additional inputs (e.g., password length).
  • Enhance user experience through structured error messaging.

Understanding the Do While Loop

Syntax

do
{
    // Code block
}
while (condition);

Key Characteristics

  • Executes at least once.
  • Condition is evaluated after execution.
  • Suitable for menu-driven programs and user input validation.
  • Prevents skipping required prompts.

In registration systems, we must ask the user to enter their email at least once. Even if the first attempt is invalid, the loop ensures repetition until the correct format is provided.


Beginner-Friendly Source Code

Lesson: User Registration Form Validation (Email Format Check)

Below is a simple console-based C# program with a namespace. This example uses Regular Expressions (Regex) for email validation.

using System;
using System.Text.RegularExpressions;

namespace UserRegistrationValidation
{
    class Program
    {
        static void Main(string[] args)
        {
            string email;
            bool isValidEmail;

            Console.WriteLine("=== User Registration Form ===");

            do
            {
                Console.Write("Enter your email address: ");
                email = Console.ReadLine();

                // Simple email pattern
                string pattern = @"^[^@\s]+@[^@\s]+\.[^@\s]+$";

                isValidEmail = Regex.IsMatch(email, pattern);

                if (!isValidEmail)
                {
                    Console.WriteLine("Invalid email format. Please try again.\n");
                }

            } while (!isValidEmail);

            Console.WriteLine("\nEmail accepted!");
            Console.WriteLine("Registration successful.");
        }
    }
}

Code Explanation

1. Namespace

UserRegistrationValidation groups related classes logically.

2. Regex Pattern

@"^[^@\s]+@[^@\s]+\.[^@\s]+$"

This pattern ensures:

  • There are characters before the @
  • There is a domain name
  • There is a dot (.) followed by a domain extension

3. Loop Logic

  • The program prompts for input.
  • It checks validity using Regex.IsMatch().
  • If invalid, the loop repeats.
  • If valid, the loop stops.

Instructions to Run the Program

  1. Open Visual Studio.
  2. Create a new Console Application.
  3. Replace the default code with the program above.
  4. Press Ctrl + F5 to run.
  5. Test various email formats.

Example Output

Example 1: Invalid First Attempt

=== User Registration Form ===
Enter your email address: userexample.com
Invalid email format. Please try again.

Enter your email address: user@gmail
Invalid email format. Please try again.

Enter your email address: user@gmail.com

Email accepted!
Registration successful.

Summary

In this lesson, we explored how to implement a do while loop in C# to validate user input in a registration form. The loop guarantees that the email prompt executes at least once and continues until a valid format is entered. By integrating regular expressions and conditional logic, we created a simple yet functional email validation system. This approach mirrors real-world software development practices where user input must be validated before data is stored or processed.


Multiple Choice Questions (Bloom’s Taxonomy Based)

1. (Remembering)

Which loop guarantees execution at least once?
A. for loop
B. while loop
C. do while loop
D. foreach loop


2. (Understanding)

Why is a do while loop suitable for email validation?
A. It checks condition first
B. It runs indefinitely
C. It ensures at least one input attempt
D. It skips invalid inputs


3. (Applying)

What method is used to validate the email format?
A. Regex.Check()
B. Regex.IsMatch()
C. Email.Validate()
D. MatchPattern()


4. (Analyzing)

What happens if the condition in the do while loop is always true?
A. The program ends immediately
B. The loop executes once
C. Infinite loop occurs
D. Compilation error


5. (Evaluating)

Which modification improves validation accuracy?
A. Remove Regex
B. Accept all inputs
C. Add stronger regex pattern
D. Remove loop


Exercises, Assessment, and Lab Exam

Introductory Paragraph

To strengthen mastery of the do while loop in C#, students must go beyond copying code and actively modify, optimize, and extend the validation logic. The following exercises and assessments are structured to develop analytical thinking and programming fluency.


Exercises

  1. Modify the program to validate both email and password length (minimum 8 characters).
  2. Add a counter to limit attempts to 3 tries.
  3. Display a custom message if the user exceeds the attempt limit.
  4. Improve the regex pattern for stricter validation.
  5. Convert the logic into a reusable method.

Assessment Activity

Create a console-based Registration System that includes:

  • Email validation
  • Password validation
  • Username validation (minimum 5 characters)

The program must:

  • Use at least one do while loop
  • Display meaningful error messages
  • Follow proper namespace structure

Lab Exam

Task: Develop a User Registration Module with the following features:

Requirements:

  • Validate email format
  • Validate password strength (uppercase, lowercase, number)
  • Limit to 5 attempts
  • Display summary of registration data
  • Organize code using methods

Evaluation Criteria:

  • Correct loop implementation (30%)
  • Validation logic accuracy (30%)
  • Code readability and structure (20%)
  • Program functionality (20%)

You may visit our Facebook page for more information, inquiries, and comments. Please subscribe also to our YouTube Channel to receive free capstone projects resources and computer programming tutorials.

Hire our team to do the project.

, , , , , , , , ,

Post navigation