C# Example: accepting form data, validating it, and displaying an error message if validation fails - Biz Tech

C# Example: accepting form data, validating it, and displaying an error message if validation fails

Listen
using System;
using System.Collections.Generic;

class Program
{
    static void Main(string[] args)
    {
        Console.Write("Enter your name: ");
        string name = Console.ReadLine();

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

        List<string> errors = new List<string>();

        if (string.IsNullOrWhiteSpace(name))
        {
            errors.Add("Name is required.");
        }

        if (string.IsNullOrWhiteSpace(email))
        {
            errors.Add("Email address is required.");
        }
        else if (!IsValidEmail(email))
        {
            errors.Add("Invalid email address.");
        }

        if (errors.Count > 0)
        {
            Console.WriteLine("The following errors occurred:");
            foreach (string error in errors)
            {
                Console.WriteLine("- " + error);
            }
        }
        else
        {
            Console.WriteLine("Name: " + name);
            Console.WriteLine("Email address: " + email);
        }
    }

    static bool IsValidEmail(string email)
    {
        try
        {
            var addr = new System.Net.Mail.MailAddress(email);
            return addr.Address == email;
        }
        catch
        {
            return false;
        }
    }
}

This example is an ASP.NET page with a form containing three text boxes (for first name, last name, and email) and a submit button. The following steps are performed:

  1. The Page_Load method is executed when the page loads.
  2. When the submit button is clicked, the SubmitButton_Click method is executed.
  3. The input values are read from the text boxes and trimmed using string.Trim().
  4. Validation is performed to ensure that all fields are filled in using string.IsNullOrEmpty(). If validation fails, an error message is displayed using a Label control and the method returns using the return keyword.
  5. Validation is performed to ensure that the email address is valid using a custom IsValidEmail() method. If validation fails, an error message is displayed using a Label control and the method returns using the return keyword.
  6. If validation passes, the form data is considered valid and can be processed in the remaining code.